Java’s ArrayList
is a Generic class that implements the List ADT. ArrayList
allows a collection of objects to be stored inside a dynamic, resizable array.
It belongs to the java.util
Java Package.
ArrayList cannot be used with primitives, so we need to use wrapper classesinstead!
Since it is a generic class, it must be supplied a type argument when initialised:
import java.util.ArrayList;
ArrayList<int> intList = new intList<>(); //Compile-time error
//Creates a new ArrayList that can only hold Integers
ArrayList<Integer> IntList = new ArrayList<>();
- It uses an Array as an instance variable
- Can be accessed via index, but not by
[]
notation. I.e. we can’t doIntList[3]
, instead we need to doIntList.get(3)
- ArrayList does not dynamically shrink, we need to use the method
trimToSize()
which reduces the array ‘capacity’.