Generic collections in Java 5.0 require the programmer to specify the types of their elements. This must be done whenever the name of a generic class or interface is used, for example, to specify the types of variables, method parameters, and method return types. Here are some example declarations of variables for lists and sets of strings:
List<String> list1;
ArrayList<String> list2;
LinkedList<String>
list3;
Set<String> set1;
HashSet<String>
set2;
For these collections, the element type parameters within the angle brackets can be any reference types. For collections that admit only comparable elements, such as sorted sets, the element type must be one that implements the Comparable interface, such as String or Integer.
Generic collections are also instantiated using the same notation for the element types, as follows:
list2
= new ArrayList<String>();
list2
= new LinkedList<String>();
set2 = new HashSet<String>();
Generic map collections require two type parameters, one for the key type and the other for the value type. The next example shows a map of strings to integers:
Map<String,
Integer> map1 = new HashMap <String, Integer>();
When the element type is also a collection, its type must
still be fully specified, as in the following sorted map of strings to sets of
strings:
SortedMap<String,
Set<String>> map2 = new TreeMap<String,
Generic collections support all of the operations to which Java programmers have become accustomed. However, once it is instantiated, a generic collection can receive only elements that are of its specified element type or subtypes of that type. The collection also can return only elements of its specified element type or subtypes of that type. These restrictions are enforced at compile time, meaning that violations produce syntax errors, not runtime exceptions. For example, the following code segment generates a syntax error on the last line:
List<String>
list1= new ArrayList<String>();
list1.add("Generics
are type safe.");
String
str = list.get(0);
list1.add(new
Integer(23)); //
Syntax error!
The use of generic collections practically eliminates casting, because most elements retrieved from a collection are of the specific type expected. The only exceptions are objects of subtypes of the element type. These objects still must be cast down before some type-specific messages are sent to them. For example, circles and rectangles are both shapes in a list of shapes, but circles might recognize some messages that other shapes donÕt.
Java 5.0 retains the older version of the java.util collections framework, now known collectively as Òraw collections.Ó However, their use is not type-safe and is discouraged, as signaled by the compilerÕs warning messages whenever they appear in a program.