检查ArrayList中是否存在值

dan*_*l__ 168 java contains 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();
Run Code Online (Sandbox Code Playgroud)

Gre*_*att 300

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

if (lista.contains(conta1)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}
Run Code Online (Sandbox Code Playgroud)

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

  • 应该在CurrentAccount中重写equals()方法,以确定它们何时是同一个对象 (8认同)
  • 在这种情况下,hashcode()也需要被覆盖.每个hashcode()契约等于对象必须具有相等的哈希码. (2认同)

小智 42

最好使用HashSetArrayList当你正在检查一个值的存在.Java文档HashSet说:"This class offers constant time performance for the basic operations (add, remove, contains and size)"

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


Sam*_*azi 15

请参阅我在这篇文章中的回答.

没有必要迭代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;
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

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

}
Run Code Online (Sandbox Code Playgroud)

  • 您正在使用==来比较字符串 (4认同)
  • 您应该使用 equals() 而不是 == 来比较字符串 `this.name.equals(employee.getName())` (2认同)

i_a*_*ero 5

contains如果提供了的实现,我们可以使用方法检查项目是否存在equalshashCode否则将使用对象引用进行相等性比较。此外,在列表中的情况containsO(n)操作,其中,因为它是O(1)HashSet这样更好地以后使用。在Java 8中,我们还可以使用流根据项目的相等性或特定属性检查项目。

Java 8

CurrentAccount conta5 = new CurrentAccount("João Lopes", 3135);
boolean itemExists = lista.stream().anyMatch(c -> c.equals(conta5)); //provided equals and hashcode overridden
System.out.println(itemExists); // true

String nameToMatch = "Ricardo Vitor";
boolean itemExistsBasedOnProp = lista.stream().map(CurrentAccount::getName).anyMatch(nameToMatch::equals);
System.out.println(itemExistsBasedOnProp); //true
Run Code Online (Sandbox Code Playgroud)