我正在尝试在代码中创建一个方法来搜索数组列表(在我的例子中为 customerList,其中包含 Customer 对象),并且如果在 ArrayList 中找不到某些内容,则会向其中添加新内容...
这是我如何设置的......
public class CustomerDatabase {
private ArrayList <Customer> customerList = null;
public CustomerDatabase() {
customerList = new ArrayList<Customer>();
}
这就是我正在尝试的方法。我正在尝试获取它,以便如果在 ArrayList 中找不到该客户,它会将给定名称“n”的 Customer 添加到 ArrayList 的末尾...
public void addCustomer(String n)
{
for(Customer c:customerList)
if (!customerList.contains(n))
customerList.add(n);
}
我知道整个 .add 和 String 都有问题,但我不确定哪里出了问题。任何输入都会很棒!
最佳答案
您将 Customer
类与其 name 属性混淆了。您无法检查 Custom
列表是否包含 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()
。根据需要进行调整。
关于java - 将 String 对象添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46458779/