将String对象添加到ArrayList [英] Adding String object to ArrayList

查看:358
本文介绍了将String对象添加到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的代码中创建一个方法,该方法搜索数组列表(在我的情况下为customerList,其中包含Customer对象),如果在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>();
  }

这是我要尝试的方法.我正在尝试获取它,以便在ArrayList中找不到的情况下,将给定名称"n"的Customer添加到ArrayList的末尾.

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);        
}

我知道整个.add然后是String出现了问题,但是我不确定哪里出错了.任何输入都会很棒!

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!

推荐答案

您正在将Customer类与其name属性混淆.您无法检查Custom的列表是否包含String,因为它永远不会包含.但是您可以检查列表中是否有任何客户拥有您要寻找的物业.如果找不到任何内容,则必须使用该字符串构造一个新对象:

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));
}

这假定Customer具有构造函数Customer(String name)和方法String getName().视需要进行调整.

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

这篇关于将String对象添加到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆