ArrayList class is resizable array implementation of the List interface.
ArrayList maintains the insertion order of element or string objects.
ArrayList allows the duplicate elements & we can randomly access elements by index.
ArrayList is not thread safe.
If multiple threads access an ArrayList instance concurrently, then arraylist must be synchronized externally.
The iterators returned by ArrayList class’s iterator & listIterator methods are fail-fast.
If ArrayList is structurally modified at any time after the iterator is created except iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException.
1. Class hierarchy of ArrayList collection:
2. Iterate or loop arraylist of String objects/elements in java (example)
package org.learn.collection.list.arrayList;
import java.util.ArrayList;
import java.util.ListIterator;
public class DemoIterationArraylist {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("archery");
arrayList.add("badminton");
arrayList.add("canoe");
arrayList.add("boxing");
arrayList.add("diving");
arrayList.add("beach volleyball");
System.out.println("\nDemo: Iterate or loop arraylist of String objects");
demoIterateMethod(arrayList);
}
private static void demoIterateMethod(ArrayList<String> arrayList) {
System.out.println("1. Iterate ArrayList using forEachRemaining:");
// Output of for loop:
// archery badminton canoe boxing diving beach volleyball
arrayList.forEach(element -> System.out.printf("%s ", element));
System.out.println("\n2. Iterate ArrayList using foreach loop:");
// Output of for loop:
//archery badminton canoe boxing diving beach volleyball
for (String element : arrayList) {
System.out.printf("%s ", element);
}
System.out.println("\n3. Iterate ArrayList using iterator:");
ListIterator<String> listIterator = arrayList.listIterator();
// Output of while loop:
//archery badminton canoe boxing diving beach volleyball
while (listIterator.hasNext()) {
System.out.printf("%s ", listIterator.next());
}
System.out.println("");
}
}
3. Output: Iterate arraylist of String objects/elements in java (example)
Demo: Iterate or loop arraylist of String objects
1. Iterate ArrayList using forEachRemaining:
archery badminton canoe boxing diving beach volleyball
2. Iterate ArrayList using foreach loop:
archery badminton canoe boxing diving beach volleyball
3. Iterate ArrayList using iterator:
archery badminton canoe boxing diving beach volleyball