24-09-2013, 02:55 PM
ArrayList, Multidimensional Arrays
Multidimensional Arrays.pdf (Size: 261.48 KB / Downloads: 267)
What’s an Array List
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
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
Adding elements to an ArrayList
The add method is used to add an element at
the “end” of an ArrayList
The method name add is overloaded
There is also a two argument version that allows
an item to be added at any currently used index
position or at the first unused position
How many elements?
The size method is used to find out how many indices
already have elements in the ArrayList
int howMany = list.size();
The set method is used to replace any existing element,
and the get method is used to access the value of any
existing element
list.set(index, "something else");
String thing = (String) list.get(index);
Note that the returned value must be cast to the proper type
size is NOT capacity
size is the number of elements currently stored in the
ArrayList
Capacity is the maximum number of elements which can
be stored. Capacity will automatically increase as
needed
Some Warnings
This lecture describes an obsolete form of
The original form of ArrayList stored Object elements,
so you had to constantly do casts
The addition of generics to the language completely
changed the use of collections like ArrayLists
To keep a modicum of backwards compatibility, raw
types allow ArrayLists to be used as originally
designed
Important: just because you can mix types together
does not mean you should!