简体   繁体   English

将String对象添加到ArrayList

[英]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... 我试图在我的代码中创建一个方法来搜索数组列表(在我的情况下为customerList,其中包含Customer对象),如果在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... 我正在尝试获取它,以便如果在ArrayList中找不到它,则将给定名称为“ n”的Customer添加到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. 我知道整个.add和String都出了问题,但是我不确定哪里出了问题。 Any input would be great! 任何输入都会很棒!

You're confusing your Customer class with its name property. 您将Customer类与其name属性混淆了。 You can't check if a list of Custom contains a String because it never will. 您无法检查Custom列表是否包含String因为它永远不会包含String 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() . 假定Customer具有构造函数Customer(String name)和方法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. Customer是一个类,您创建了一个Customer类类型的数组列表。没有直接的方法可以将name(String)与Customer类对象进行比较。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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