«^»
7.2. Use of interfaces with collection classes

Java's Collections API provides classes that can be used for representing collections of objects, such as lists, sets and maps. It provides two classes for each of these. For lists, it provides classes called ArrayList and LinkedList; for sets, it provides classes called HashSet and TreeSet; and, for maps, it provides classes called HashMap and TreeMap. Often your choice of the class will be determined by the particular operations that you want to perform: one of the classes performs faster than the other.

Suppose we want to represent a list of objects. If we are using the Collections API, we have a choice between using an ArrayList and a LinkedList:


The ArrayList class performs well in most situations. However, the LinkedList class performs better than ArrayList when the operations that dominate involve adding or removing items at the ends of the list.

Having made a choice over the class, then the operations that you can perform on the list are the same. So, if tList points to an ArrayList object or a LinkedList object, we can perform operations such as:

tList.add("Tom");
tList.add("Harry");
tList.add(1, "Dick");
tList.remove(1);
tList.set(1, "Dick");
String tString = (String)tList.get(1);

Before executing this code, we need to create the list object. The code we use for this depends on whether we want an ArrayList or a LinkedList. So we can choose between:

ArrayList tList = new ArrayList();

or:

LinkedList tList = new LinkedList();

However, the above is not regarded as good programming style. Sun's documentation for the Collections API encourages you to code in terms of interfaces called List, Set and Map instead of writing code in terms of specific classes (such as ArrayList and LinkedList).

So use either:

List tList = new ArrayList();

or:

List tList = new LinkedList();

Instead of using a variable tList which is of a specific class type (ArrayList or LinkedList), we are now using a variable tList which is of the interface type List. A variable that is of an interface type may point to any object that is of a class that implements that interface.

If a list object has to be passed as an argument to a method, then this style of programming recommends that the parameter be of the interface type rather than of the specific class type. So, instead of the method having a header like:

public void processList(ArrayList pArrayList);

it should be:

public void processList(List pList);

With this style of programming, most of the code is written in terms of the List interface. The only place where either ArrayList or LinkedList has to be mentioned is when we create the list object, i.e., the commitment to use an ArrayList instead of a LinkedList (or vice-versa) only appears where the object is created.