class MailList {
public static void main(String args[]) {
LinkedList<Address> ml = new LinkedList<Address>();
// Add elements to the linked list.
ml.add(new Address("J.W. West", "11 Oak Ave",
"Urbana", "IL", "61801"));
ml.add(new Address("Ralph Baker", "1142 Maple Lane",
"Mahomet", "IL", "61853"));
ml.add(new Address("Tom Carlton", "867 Elm St",
"Champaign", "IL", "61820"));
// Display the mailing list.
for(Address element : ml)
System.out.println(element + "\n");
The output from the program is shown here:
J.W. West
11 Oak Ave
Urbana IL 61801
Ralph Baker
1142 Maple Lane
Mahomet IL 61853
Tom Carlton
867 Elm St
Champaign IL 61820
Aside from storing a user-defined class in a collection, another important thing to notice
about the preceding program is that it is quite short. When you consider that it sets up a linked
list that can store, retrieve, and process mailing addresses in about 50 lines of code, the power
of the Collections Framework begins to become apparent. As most readers know, if all of this
functionality had to be coded manually, the program would be several times longer. Collections
offer off-the-shelf solutions to a wide variety of programming problems. You should use them
whenever the situation presents itself.
The RandomAccess Interface
The RandomAccess interface contains no members. However, by implementing this interface,
a collection signals that it supports efficient random access to its elements. Although a collection
might support random access, it might not do so efficiently. By checking for the RandomAccess
interface, client code can determine at run time whether a collection is suitable for certain
types of random access operations--especially as they apply to large collections. (You can use
instanceof to determine if a class implements an interface.) RandomAccess is implemented
by ArrayList and by the legacy Vector class, among others.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks