Array List
Array List
ArrayList
Aug 9, 2007 1
Whats an Array List
ArrayList is
a class in the standard Java libraries that can hold
any type of object
an object that can grow and shrink while your
program is running (unlike arrays, which have a
fixed length once they have been created)
In general, an ArrayList serves the same
purpose as an array, except that an
ArrayList can change length while the
program is running
Aug 9, 2007 2
The ArrayList Class
The class ArrayList is implemented using
an array as a private instance variable
When this hidden array is full, a new larger hidden
array is created and the data is transferred to this
new array
Aug 9, 2007 8
Methods in the Class
ArrayList
The tools for manipulating arrays consist only
of the square brackets and the instance
variable length
ArrayLists, however, come with a
selection of powerful methods that can do
many of the things for which code would have
to be written in order to do them using arrays
Aug 9, 2007 21
Why are Some Parameters of Type
Base_Type and Others of type Object
When looking at the methods available in the ArrayList class,
there appears to be some inconsistency
In some cases, when a parameter is naturally an object of the
Aug 9, 2007 24
Copying an ArrayList
// create an ArrayList of Integers
ArrayList<Integer> a = new ArrayList<Integer>( );
a.add(42); a.add(57); a.add(86);
Assignment doesnt work
As weve seen with any object, using assignment
just makes two variables refer to the same ArrayList.
ArrayList<Integer> b = a;
b 42 57 86
Stack Heap
Aug 9, 2007 25
Copying an ArrayList
ArrayList<Integer> b = a.clone( );
42 57 86
a
Stack Heap
Aug 9, 2007 26
Copying an ArrayList
We need to manually make a deep copy
ArrayList<Integer> b = a.clone( );
for( int k = 0; k < b.size( ); k++)
b.set(k, a.get(k));
42 57 86
42 57 86
a
Stack Heap
Aug 9, 2007 27
ArrayList vs Array
Why use an array instead of an ArrayList
Aug 9, 2007 29
The Vector Class
The Java standard libraries have a class
named Vector that behaves almost exactly
the same as the class ArrayList
In most situations, either class could be used,
however the ArrayList class is newer
(Java 5), and is becoming the preferred class