ArrayLists

ArrayLists are dynamic arrays that can grow and shrink.

Example:
ArrayList<Integer> list = new ArrayList<>();

list.add(5);
list.add(10);
list.remove(0);

System.out.println(list.get(0));
System.out.println(list.size());
Elements are added and removed, and methods are used to access elements and check size.

Important difference:
Arrays use length, ArrayLists use size().

ArrayList methods:

  • add(obj)
    Adds an element to the end of the list.

  • add(index, obj)
    Inserts an element at a specific index.

  • get(index)
    Returns the element at the given index.

  • set(index, obj)
    Replaces the element at the given index.

  • remove(index)
    Removes the element at the given index and shifts the rest left.

  • size()
    Returns the number of elements in the list.

When you remove elements from an ArrayList, you should traverse the list backwards to avoid skipping elements.