Java 5.0 - Generics

This is the major change in Java 5.0. Generics allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting.

In other words, when you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection. Please refers to

for details.

Below lists modifications in lvg for Javadoc 5.0:

  • Vector<E>, LinkedList<E>, ArrayList<E>, HashSet<E>, Enumeration, Iterator, etc.

    E stands for elements in the collection class.
    Add the type of element and remove the casting.

    Example:

    
    Vector<String> foo = new Vector<String>;
    
    ...
    
    for(int i = 0; i < foo.size(); i++)
    {
    String temp = foo.elementAt(i);
    }
    
  • Hashtable<K, V>, Map<K, V>, etc.

    K stands for key and V stand for value in the key value pair.
    Add the type of key and value.

    Example:

    
    Hashtable<String, String> foo = new Hashtable<String, String>;
    
    ...
    
    String key = "key";
    String value = "value";
    
    foo.put(key, value);
    
  • Comparator<T>

    T represents one or more type parameters
    Add the type parameters in the new comparator class and type when use it.

    Example:

    
    public class fooComparator<T> implements Comparator<T>
    {
    public int compare(T o1, To2)
    {
    ...
    }
    
    ...
    
    fooComparator<String> foo = new fooComparator<String>();
    ...
    }
    
  • Replace Array with ArrayList

    The component type of an array object may not be a type variable or parameter type, unless it is an (unbounded) wildcard type.

    Example:

    
    ArrayList<Vector<String>> foo = new ArrayList<Vector<String>>(10);
    
    for(int i = 0; i < 10; i++)
    {
    foo.add(i, new Vector<String>());
    }