检查ArrayList中是否存在值

问题

如何检查ArrayList中写入的值是否存在?

List<CurrentAccount> lista = new ArrayList<CurrentAccount>();

CurrentAccount conta1 = new CurrentAccount("Alberto Carlos", 1052);
CurrentAccount conta2 = new CurrentAccount("Pedro Fonseca", 30);
CurrentAccount conta3 = new CurrentAccount("Ricardo Vitor", 1534);
CurrentAccount conta4 = new CurrentAccount("João Lopes", 3135);

lista.add(conta1);
lista.add(conta2);
lista.add(conta3);
lista.add(conta4);

Collections.sort(lista);

System.out.printf("Bank Accounts:" + "%n");
Iterator<CurrentAccount> itr = lista.iterator();
while (itr.hasNext()) {
    CurrentAccount element = itr.next();
    System.out.printf(element + " " + "%n");
}
System.out.println();

#1 热门回答(251 赞)

只需使用ArrayList.contains(desiredElement)。例如,如果你正在寻找示例中的conta1帐户,则可以使用以下内容:

if (lista.contains(conta1)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}

**编辑:**注意,为了使其正常工作,你需要正确覆盖equals()hashCode()方法。如果你正在使用Eclipse IDE,那么你可以通过首先打开CurrentAccount对象的源文件并选择Source > Generate hashCode() and equals()...来生成这些方法。


#2 热门回答(37 赞)

当你检查是否存在值时,最好使用aHashSetArrayList。 Java文档forHashSetsays:"This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains()可能必须迭代整个列表才能找到你要查找的实例。


#3 热门回答(11 赞)

请参阅我的答案this post

没有必要迭代List只需覆盖equals方法。

使用equals而不是==

@Override
public boolean equals (Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
        result = false;
    } else {
        EmployeeModel employee = (EmployeeModel) object;
        if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation())   && this.age == employee.getAge()) {
            result = true;
        }
    }
    return result;
}

这样叫:

public static void main(String args[]) {

    EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
    EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
    EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);

    List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
    employeeList.add(first);
    employeeList.add(second);
    employeeList.add(third);

    EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
    System.out.println("Check checkUserOne is in list or not");
    System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));

    EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
    System.out.println("Check checkUserTwo is in list or not");
    System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));

}