1 of 10

The ArrayList

Chapter 14.2

2 of 10

What is an ArrayList?

  • An ArrayList is a variable-length array of object references.

  • ArrayLists dynamically increase or decrease in size. They are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

3 of 10

ArrayList Methods/Operations

  • The ArrayList uses the same basic set of methods used by a LinkedList, so they have the same logical behavior.

  • Uses:
    • Index-based operations
    • Content-based operations

4 of 10

The ArrayList Constructors

  • ArrayList has these constructors: �

ArrayList( ) // empty list�

ArrayList(Collection c) // initialized with elements from list c�

ArrayList(int capacity) // list with specified initial capactity.

*** The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

5 of 10

Creating the ArrayList

import java.util.ArrayList;

ArrayList<type> name = new ArrayList<type>();

6 of 10

Changing Capacity Manually

  • The capacity of an ArrayList object can be changed manually by calling ensureCapacity( )�
  • You might want to do this if you know in advance that you will be storing many more items in the collection that it can currently hold.

  • Because adding extra positions in the ArrayList are costly in terms of time, preventing unnecessary ones improves performance.

7 of 10

Changing Capacity

void ensureCapacity(int cap)

    • Here, cap is the new capacity. This can increase the capacity of the ArrayList.
  • void trimToSize( )
    • Trims the array to exactly the number of items it is currently holding.

8 of 10

Obtaining an Array from an ArrayList

  • Several reasons exist why you might want to convert a collection into an array such as:�
    • To obtain faster processing times for certain operations.
    • To pass an array to a method that is not overloaded to accept a collection.

Method:

array[] = listName.toArray();

9 of 10

ArrayList

  • Implements List interface operations.
  • Guarantees constant-time access to an element at any position in the List.
  • List operations run faster on ArrayLists.
  • Linear time insertions at head or tail.

LinkedList

  • Implements List interface operations.
  • Provides linear access to any element other than the first or last one.
  • List operations run slower on LinkedLists.
  • Guarantee constant time insertions and removals at the head or tail.

10 of 10

And the Winner is…

  • Use a LinkedList when elements are accessed, inserted, or removed at the head or the tail only.
  • Use ArrayLists for almost all other cases.