- Prior to 1.5:
Vector v = new Vector();
while (...) { // adding String's to the vector
String s = ...;
v.add(s);
}
...
Iterator iter = v.iterator();
while (iter.hasNext()) { // Extracting elements of the vector
String s = (String)iter.next(); // downcast needed
...
}
- Collections can now be declared with their element types:
Vector<String> v = new Vector<String>():
- The compiler enforces this declaration
Vector<String> v = new Vector<String>():
v.add(new Integer(5)); // compiler error
- Collection is then guaranteed to be homogeneous
- Above vector can only contain Strings
- Downcasting can then be done automatically by the compiler
Vector<String> v = new Vector<String>():
String s = ...;
v.add(s);
...
String s2 = v.elementAt(0); // no need for downcast-- compiler takes care of it
- Collection processing is now much simpler
Vector<String> v = new Vector<String();
while (...) { // adding String's to the vector
String s = ...;
v.add(s);
}
...
Iterator<String> iter = v.iterator();
while (iter.hasNext()) { // Extracting elements of the vector
String s = iter.next(); // no downcast needed
...
}
- Users can create their own generic class definitions as well