检查ArrayList中是否存在值 [英] Check if a value exists in ArrayList

查看:633
本文介绍了检查ArrayList中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I can check if a value that is written in scanner exists in an 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帐户,您可以使用以下内容:

Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:

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

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

Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount object and the selecting Source > Generate hashCode() and equals()...

这篇关于检查ArrayList中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆