如何检查扫描仪中写入的值是否存在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对象的源文件并选择来生成这些方法。Source > Generate hashCode() and equals()...
CurrentAccount
Source > Generate hashCode() and equals()...