问题描述
我怎么可以检查,如果是写在扫描仪的值的ArrayList中存在LISTA?
列表< CurrentAccount> LISTA =新的ArrayList< CurrentAccount>();CurrentAccount conta1 =新CurrentAccount(卡洛斯·阿尔贝托,1052);
CurrentAccount conta2 =新CurrentAccount(佩德罗·丰塞卡,30);
CurrentAccount conta3 =新CurrentAccount(里卡多维托尔,1534);
CurrentAccount conta4 =新CurrentAccount(若昂·洛佩斯,3135);lista.add(conta1);
lista.add(conta2);
lista.add(conta3);
lista.add(conta4);Collections.sort(LISTA);System.out.printf(银行账户+%N);
迭代器< CurrentAccount> ITR = lista.iterator();
而(itr.hasNext()){
CurrentAccount元= itr.next();
System.out.printf(元素++%N);
}
的System.out.println();
只需使用ArrayList.contains(desiredElement).例如,如果你正在寻找从例如conta1帐户,您可以使用类似:
如果(lista.contains(conta1)){
的System.out.println(账户找到了);
}其他{
的System.out.println(找不到帐户);
}
编辑:
注意,为了这个工作,你需要正确地重写equals()和<一个href=\"http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#hash$c$c%28%29\">hash$c$c()方法。如果您使用的是Eclipse IDE,那么你可以有首先打开你的 CurrentAccount
对象的源文件和选择来源和GT产生的这些方法;生成散列code()和equals()...
how i can check if a value that is written in scanner exists in arrayList lista?
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();
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");
}
Edit: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中存在的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!