Java Reference
In-Depth Information
Lists
The Collections Framework has several implementations of the List interface, including
ArrayList , LinkedList , Vector , and Stack . Instantiating a list using generics requires
specifying the data type that the list contains. The use of generics is seen in the class
declaration of the list classes. For example, the Vector class is declared as
public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
The E is a generic and represents a placeholder for the data type of the elements to be
stored in the Vector . You specify the data type for E when constructing a Vector . For
example, a Vector of Date objects is instantiated as
Vector<Date> december = new Vector<Date>();
Only Date objects can be stored in the december vector, and all get methods of december
return Date references.
Let's look at an example of using lists. The following ArrayList can only contain
String types:
List<String> list = new ArrayList<String>();
The following statements demonstrate some of the basic methods in the List interface
for adding and removing items from list . Study the code and see if you can determine the
result:
7. list.add(“SD”);
8. list.add(0, “NY”);
9. list.set(1, “FL”);
10. list.remove(“NY”);
11. list.remove(0);
The sequence of events for the previous statements is as follows:
1. The ArrayList is initially empty. Line 7 adds “SD” to the end of list, which is at index 0 .
2. Line 8 inserts “NY” at index 0 . The list now contains “NY” and “SD“ .
3. Line 9 sets “FL” at index 1 , replacing “SD“ . The list now contains two String objects:
“NY” and “FL“ .
4. Line 10 removes “NY” “from the list , leaving just “FL“ .
5. Line 11 removes the element at index 0 , which is “FL“ . The ArrayList is now empty
again.
The List interface contains other useful methods. Using the same ArrayList named
list from the previous code, see if you can determine the output of the following
statements:
Search WWH ::




Custom Search