简体   繁体   中英

Adding String object to ArrayList

I am trying to create a method in my code that searches through an array list (in my case customerList, which contains Customer objects) and will add something new to it if that something isn't found in the ArrayList...

Here is how I have it all set up....

public class CustomerDatabase {

   private ArrayList <Customer> customerList = null;

   public CustomerDatabase() {
       customerList = new ArrayList<Customer>();
  }

and this is the method I'm trying to make. I'm trying to get it so that it will add a Customer with given name "n" to the end of the ArrayList if it isn't found in the ArrayList...

public void addCustomer(String n)
{
   for(Customer c:customerList)
      if (!customerList.contains(n))
         customerList.add(n);        
}

I'm aware that something is wrong with the whole .add and then a String thing but I'm not sure where I went wrong. Any input would be great!

You're confusing your Customer class with its name property. You can't check if a list of Custom contains a String because it never will. But you can check if any customers in the list have the property you're looking for. If you don't find any, then you have to construct a new object with that string:

public void addCustomer(String name) {
    for (Customer c : customerList) {
        if (c.getName().equals(name)) {
            // duplicate found
            return;
        }
    }
    // no duplicates; add new customer
    customerList.add(new Customer(name));
}

This assumes Customer has a constructor Customer(String name) and a method String getName() . Adapt as necessary.

Customer is a class and you made an array list of Customer class type.there is no direct way to compare name(String) with Customer class object.

You should change your code like-

public void addCustomer(String name) {
for (Customer c : customerList) {
    if (!c.getName().equals(name)) {
        Customer c=new Customer();
        c.setName(name);
        customerList.add(c);
    }
}   

}

And in Customer Class

Class Customer{
private String name;
//getter and setter method for name.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM