ArrayList in Java
ArrayList in Java
1) Creating an ArrayList
stringList.remove(0);
stringList.remove(item);
stringList.set(0,"Item2");
11) Clearing all data from ArrayList
ArrayList in Java provides clear () method which removes all of the elements from this list. Below code will
remote all elements from our stringList and make the list empty. You can reuse Java ArrayList after clearing
it.
stingList.clear();
12) Converting from ArrayList to Array in Java
Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a)
method returns an array containing all of the elements in this list in proper sequence (from first to last
element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a
new array of the same runtime type is allocated for this purpose.
If you want to convert ArrayList back to Array than see 3 ways to convert array into
arraylist in Java
13) Creating Synchronized ArrayList
Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you
can use Collections utility class for this purpose as shown below.
//////////////////////////////////////////////////////////
how i can check if a value that is written in scanner exists in arrayList lista?
List<CurrentAccount> lista = new ArrayList<CurrentAccount>();
CurrentAccount
CurrentAccount
CurrentAccount
CurrentAccount
conta1
conta2
conta3
conta4
=
=
=
=
new
new
new
new
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();
java arraylist
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");
}