Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

486 Part II: The Java Library


These two improvements are made possible because each collection class has been given
a type parameter that specifies the type of the collection. For example,ArrayListis now
declared like this:

class ArrayList<E>

Here,Eis the type of element stored in the collection. Therefore, the following declares an
ArrayListfor objects of typeString:

ArrayList<String> list = new ArrayList<String>();

Now, only references of typeStringcan be added tolist.
TheIteratorandListIteratorinterfaces are now also generic. This means that the type
parameter must agree with the type of the collection for which the iterator is obtained.
Furthermore, this type compatibility is enforced at compile time.
The following program shows the modern, generic form of the preceding program:

// Modern, generics version.
import java.util.*;

class NewStyle {
public static void main(String args[]) {

// Now, list holds references of type String.
ArrayList<String> list = new ArrayList<String>();

list.add("one");
list.add("two");
list.add("three");
list.add("four");

// Notice that Iterator is also generic.
Iterator<String> itr = list.iterator();

// The following statement will now cause a compile-time error.
// Iterator<Integer> itr = list.iterator(); // Error!

while(itr.hasNext()) {
String str = itr.next(); // no cast needed

// Now, the following line is a compile-time,
// rather than run-time, error.
// Integer i = itr.next(); // this won't compile

System.out.println(str + " is " + str.length() + " chars long.");
}
}
}

Now,listcan hold only references to objects of typeString. Furthermore, as the following
line shows, there is no need to cast the return value ofnext( )intoString:

String str = itr.next(); // no cast needed

The cast is performed automatically.
Free download pdf