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, ArrayList is now
declared like this:
class ArrayList<E>
Here, E is the type of element stored in the collection. Therefore, the following declares an
ArrayList for objects of type String:
ArrayList<String> list = new ArrayList<String>();
Now, only references of type String can be added to list.
The Iterator and ListIterator interfaces 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, list can hold only references to objects of type String. Furthermore, as the following
line shows, there is no need to cast the return value of next( ) into String:
String str = itr.next(); // no cast needed
The cast is performed automatically.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home