Java Reference
In-Depth Information
The
java.util
package provides two implementations of
ListArrayList
and
LinkedList
.
21.6.1.
ArrayList
ArrayList
is a good basic list implementation that stores its elements
in an underlying array. Adding and removing elements at the end is
very simple
0
(1). Getting the element at a specific position is also
0
(1).
Adding and removing elements from the middle is more expensive
0
(
n-
i
) where
n
is the size of the list and
i
is the position of the element
being removed. Adding or removing the element requires copying the
remainder of the array one position up or down.
An
ArrayList
has a
capacity,
which is the number of elements it can hold
without allocating new memory for a larger array. As you add elements
they are stored in the array, but when room runs out, a replacement
array must be allocated. Setting your initial capacity correctly can im-
prove performance. If the initial size of the data is significantly smaller
than its final size, setting the initial capacity to a larger value reduces
the number of times the underlying array must be replaced with a larger
copy. Setting the size too large can waste space.
ArrayList
has three constructors:
public
ArrayList()
Creates a new
ArrayList
with a default capacity.
public
ArrayList(int initialCapacity)
Creates a new
ArrayList
that initially can store
initialCapacity
elements without resizing.
public
ArrayList(Collection<? extends E> coll)