Next: Wrapper classes. Up: The ArrayList class. Previous: None.
The ArrayList class is intended for holding a sequence of elements. Actually, it bears a strong resemblance to an array, but in many cases the ArrayList class is more convenient. Namely, a ArrayList automatically grows and shrinks as you add and remove objects.
The ArrayList is a library class. (It's found in java.util, but I recommend the abridged version in csbsju.cs160 in this class.) To create one, you declare a variable of type ArrayList, and set it up to point to a new ArrayList.
When you create an ArrayList object, it initially is holding nothing.ArrayList vec = new ArrayList();
The ArrayList class has a lot of methods. I'm not going to list them all here. The documentation is much more helpful on this point.
The ArrayList class provides three important methods for putting new data into the ArrayList.
ArrayList count = new ArrayList(); for(int i = 1; i <= 10; i++) count.add("" + i);
NOTE: An ArrayList object can hold only objects. It can't hold primitive types, like int. We'll see a workaround soon - but it's simply a workaround.
Three methods are particularly useful for accessing information about an ArrayList object.
The get() method is a little irritating: The ArrayList class is written to hold a sequence of objects of any type; as far as ArrayList knows, all its elements are simply in the Object class. Thus, you cannot do the following.
The get() method returns an Object, and Java won't automatically cast down the inheritance hierarchy. You need to have an explicit casting operator to make this work.String str = count.get(5);
String str = (String) count.get(5);
It's worth noting that indexOf() uses the equals() method to determine whether it has found a match. Thus, count.indexOf("5") returns 4, even though "4" != count.get(4), since the two objects (that happen to represent the same string) are at different locations in memory.
You can also remove elements from an ArrayList object. This would be the inverse of adding something into the ArrayList.
ArrayLists are very useful. In many cases where we used an array in the past, an ArrayList would be more convenient - for example, they would be very appropriate for the Very Small Video lab (but you're not allowed to go back and use ArrayLists for it!). If the program used an ArrayList instead, then the store wouldn't have an arbitrary limit on how many videos and customers the store could have..
When should you use an array, and when should you use an ArrayList?
Next: Wrapper classes. Up: The ArrayList class. Previous: None.