The ArrayList ClassΒΆ

Luckily Java has a class that handles this type of thing. It is called ArrayList. It implements the List interface using an array. This means that it contains or inherits the code for the methods defined in the List interface. I will describe what inheritance means in more detail later. Java actually has several classes that implement the List interface (provide method bodies for the abstract methods defined in the interface). See the Java documentation above for all the classes that implement the List interface (ArrayList, LinkedList, Stack, Vector, etc).

To be able to plug in different implementing classes, you should declare the variable type to be List and the only place you should use the class ArrayList is when you actually create the list as shown below. This minimizes the number of places you have to change your code if you change your mind and use a different implementing class in the future.

import java.util.*;  // import all classes in this package.
List<String> nameList = new ArrayList<String>();
nameList.add("Diego");
nameList.add("Grace");
nameList.add("Deja");

This code creates an object variable called nameList that will refer to a List of String objects and sets its reference to an object of the ArrayList class that can hold String objects. The <String> tells Java the type of objects that you will have in your List. If you try to put objects of other types in the list you will get a run-time error.

Check your understanding

8-3-1: What will print when the following code executes?

List<Integer> list1 = new ArrayList<Integer>();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.set(2, new Integer(4));
list1.add(2, new Integer(5));
list1.add(new Integer(6));
System.out.println(list1);





8-3-2: What will print when the following code executes?

List<Integer> list1 = new ArrayList<Integer>();
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
list1.remove(1);
System.out.println(list1);





8-3-3: What will print when the following code executes?

List<Integer> numList = new ArrayList<Integer>();
numList.add(new Integer(1));
numList.add(new Integer(2));
numList.add(new Integer(3));
numList.set(2,new Integer(4));
numList.add(1, new Integer(5));
numList.add(new Integer(6));
System.out.println(numList);