But with an array, we have to specify its size ahead of time. This
limits flexibility!
Fortunately, Java gives us an alternative, the ArrayList.
ArrayList is a Java class designed to hold a group of objects.
It automatically resizes to hold the number of objects you give it.
Before ArrayLists, we used Vectors, which are very similar. ArrayLists
are slightly more efficient. Feel free to use either one.
ArrayLists hold objects of class Object,
the supeclass of all classes.
So, to use ArrayLists, we usually need to cast these objects to a more
usable form once we retrieve them.
ArrayList methods:
add(Object o) allows us to add the object to the end of the ArrayList.
size() gives us the number of elements in an ArrayList. This comes
in handy when using a loop.
If you need to put an object into an ArrayList at a specific position,
where another object already exists, use set(int i, Object o), where i
is the position in the ArrayList in which you want to add your object.
get(int i) returns the object at position i, as an instance of class Object.
You must cast it.