THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

ArrayList also provides some methods to manage capacity:


public voidtrimToSize()

Sets the capacity to be exactly the current size of the list. If the capacity is
currently larger than the size, a new, smaller underlying array will be
allocated and the current values copied in. You can thus reduce the amount of
memory necessary to hold the list, although at some cost.

public voidensureCapacity(int minCapacity)

Sets the capacity to minCapacity if the capacity is currently smaller. You
can use this if you are about to add a large number of elements to the list, and
so ensure the array will be reallocated at most once (when
ensureCapacity is invoked) rather than possibly multiple times while
the elements are added.

21.6.2. LinkedList


ALinkedList is a doubly linked list whose performance characteristics are virtually the reverse of
ArrayList: Adding an element at the end is 0(1), but everything else is swapped. Adding or removing an
element in the middle is 0(1) because it requires no copying, while getting the element at a specific position i
is 0(i) since it requires starting at one end and walking through the list to the ith element.


LinkedList provides two constructors and adds methods that are useful and efficient for doubly linked
lists:


publicLinkedList()

Creates a new empty LinkedList.

publicLinkedList(Collection<? extends E> coll)

Creates a new LinkedList whose initial contents are those of coll. The
order is that returned by the collection's iterator.

public EgetFirst()

Returns the first object in this list.

public EgetLast()

Returns the last object in this list.

public EremoveFirst()

Removes the first object in this list.

public EremoveLast()

Removes the last object in this list.

public voidaddFirst(E elem)
Free download pdf