Alex Rivera | Logout

Check if a value exists in ArrayList

Asked 2010-12-09T23:11:52.463
223

How can I check if a value 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();
Edit
Report

1 Answer

54

Better to use a HashSet than an ArrayList when you are checking for existence of a value.

Java docs for HashSet says

This class offers constant time performance for the basic operations (add, remove, contains and size)

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

answered 2010-12-10T04:23:32.030

Your Answer