The Java Collections API

By Raul Rios

Arrays are good and fast, but they are static (once they are created they can’t grow). In this lesson we’re going to review three hierarchically related types from the Java Collections API that provide dynamic data structures:

Type

extends

implements

Description

interface Collection

Iterable

–

General dynamic collection of elements that is iterable

interface List

Collection

–

Dynamic collection providing also positional access

class ArrayList

ArrayList

List

RandomAccess

Implementation of List providing fast positional access

The Collection Interface

The Collection interface is used when maximum generality is desired. The following table lists the main methods of this interface:

Returns the index of the first (or last) occurrence of the specified element in this list, or -1 if the element is not found

(1) All index-based operations throw an exception if the specified index is out of range

You can think of a List as an ordered collection that allows duplicates. Two List objects are equal if they contain the same (according to equals method) elements and in the same order.

The ArrayList Class

The ArrayList class is probably the most used implementation of the List interface. It is internally backed up by an array and provides fast (constant-time) positional access.

Since it is a dynamic collection that grows automatically, you don’t have to worry about its size, except if you try to add elements at a specific index (in order to add an element at index i the ArrayList must have at least i elements or an exception will be thrown).

1

2

3

4

5

6

7

// ArrayList example

ArrayList<Integer>al=newArrayList<>();

al.add(newInteger(1));

al.add(0,newInteger(2));

al.remove(1);

The Vector class is the equivalent thread-safe collection that it’s used when synchronization is needed. Because of this synchronization overhead it’s slightly slower than ArrayList.

You can create an ArrayList or a Vector object using the existing data in another Collection object to initially populate it:

1

2

3

List<String>list=newArrayList<String>(collection);

That’s all coders! If you have any comments or questions, you can drop me a line or leave a comment below and I will be pleased to help you.

In case you’re looking for a complete (but still short, precise and to-the-point) study guide to help you get your valuable Oracle® Java Programmer certification, including many tricky real-exam-like questions, study sheets, and other bonuses, then the Java Certification Roadmap book is your book.

Finally, if you found this content useful and know more programmers, colleagues or friends that may be interested in getting the Java Certification, click one of the buttons belowclick the button on the bottom left corner of your screen to let them know about the Java Certification Roadmap.