检查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(); 

只要使用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对象的源文件并selectSource > Generate hashCode() and equals()...来生成这些方法Source > Generate hashCode() and equals()...

当您检查值的存在时,最好使用HashSet不是ArrayListHashSet Java文档说: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains()可能不得不迭代整个列表来查找您正在查找的实例。

你好只是指我的答案在这个post是解释在这里没有必要迭代列表只是覆盖等于方法。

更新 equels方法,而不是==

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