Java Reference
In-Depth Information
SE 5, an individual
ArrayList
can hold only references to instances of a single,
specifi ed class. (This restriction can be circumvented by specifying the base
type to be
Object
, the ultimate superclass, if a heterogeneous collection of
objects is truly required.) Class
ArrayList
is contained within package
java.util
,
so this package should be imported by any program wishing to make use of
ArrayList
s.
Constructor overloading allows us to specify the initial size if we wish, but the
simplest form of the constructor takes no arguments and assumes an initial capacity
of ten. In common with the other member classes of Java's Collection Framework,
the class of elements that may be held in an
ArrayList
structure is specifi ed in angle
brackets after the collection class name, both in the declaration of the
ArrayList
and
in its creation. For example, the following statement declares and creates an
ArrayList
that can hold
String
s:
ArrayList<String> stringArray = new ArrayList<String>();
This syntax was applicable up to Java SE 6 and is accepted in Java SE 7, but the
latter also allows a shortened version of the above syntax, in which the type of ele-
ments held inside the collection class is not repeated. Instead, the angle brackets
immediately preceding the brackets for the collection class constructor are left
empty:
ArrayList<String> nameList = new ArrayList<>();
Objects are added to the end of an
ArrayList
via method
add
and then refer-
enced/retrieved via method
get
, which takes a single argument that specifi es the
object's position within the
ArrayList
(numbering from zero, of course). Since
the elements of an
ArrayList
(and of any other collection class) are stored as
Object
references (i.e., as references to instances of class
Object
) whilst in the
ArrayList
, it used to be the case that elements of the
ArrayList
had to be typecast
back into their original type when being retrieved from the
ArrayList
, but the
'auto-unboxing' feature introduced by Java SE 5 means that they can be retrieved
directly now.
Example (Assumes that
ArrayList
is empty at start)
String name1 = "Jones";
nameList.add(name1);
String name2 = nameList.get(0);
After execution of the above lines,
name1
and
name2
will both reference the
string 'Jones'.
An object may be added at a specifi c position within an
ArrayList
via an over-
loaded form of the
add
method that takes two arguments, the fi rst of which specifi es
the position at which the element is to be added.
Example
nameList.add(2, "Patterson"); //3rd position.
Search WWH ::
Custom Search