| |
The List Interface | page 3 of 7 |
The List interface from the java.util package gives a formal description of a list. The Java library also provides two classes, ArrayList and LinkedList that implement the List interface.
Like ArrayList and other collection classes, LinkedList can store objects that have the Object data type. Since any class extends Object , you can put any kind of object into a list. Since the methods that retrieve values from the list return an object, you have to cast the object back into its original type when it is retrieved from the list. For example:
List classList = new LinkedList();
classList.add("APCS");
...
String favoriteClass = (String)classList.get(1);
These classes assume that the values in the list have the type Object . To put primitive data types such as int s or double s into the list, you need to first convert them to into objects using the appropriate wrapper class, Integer or Double . For example:
List numList = new LinkedList();
numList.add(new Integer(23));
numList.add(new Double(3.14159));
...
int i = ((Integer)numList.get(0)).intValue();
double d = ((Double)numList.get(1)).doubleValue();
It is assumed that the elements in the list are indexed starting from 0. "Logical" indices are used even if a list is not implemented as an array. Methods that use indices generate a run-time error if and index is out of bounds.
A few commonly used List methods are summarized below.
boolean add(Object element)
// Appends the given element to the end of this list
void add(int index, Object element)
// Inserts the specified element at the specified position
int size()
// Returns the number of elements in this list
Object get(int index)
// Returns the element at the specified position in this list
Object set(int index, Object element)
// Replaces the element at the specified position in this list
// with the specified element
Object remove(int index)
// Removes the first occurrence in this list of the specified
// element
|