Adding String object to ArrayList

无人久伴 提交于 2019-12-25 11:59:15

问题


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!


回答1:


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.




回答2:


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.
}


来源:https://stackoverflow.com/questions/46458779/adding-string-object-to-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!