Generic Programming
Home ] Up ] Introduction ] Java Resources ] The Java Environment ] Java Language Fundamentals ] Objects and Arrays ] Operators ] Statements ] Classes and Objects ] Packages ] Inheritance & Polymorphism ] The Java Class Library ] Inner Classes ] Graphics Programming ] Events ] Swing GUI Components ] Applets ] Exceptions ] [ Generic Programming ]

 

Concept
The Collections Framework

 

How many times have you seen code that does something like:

    ArrayList list = new ArrayList();
    
    ...
    for (int i = 0; i < list.size(); i++)
    {
      String name = (String) list.get(i); // Note required cast
      System.out.println(i + ": " + name);
    }
    for (Iterator iter = list.iterator(); iter.hasNext(); )
    {
      String name = (String) iter.next(); // Note required cast
      System.out.println(name);
    }

where we are forced to do an explicit typecast, because we "know" the type that is being returned from some method (in this case, from a Collections class) ?

This kind of coding is annoying, and error-prone.  If the type of object that is actually returned does not match what you thought, then the JVM will throw a ClassCastException.

It would be nice to have some mechanism where this kind of thing could be specified and checked at compile time, thus avoiding the error-prone practices exemplified above.

Enter Generic Programming!

JDK 1.5 (5.0) introduced Generic Programming (a.k.a. Generics) to solve this problem.

Generics allow you to write code that is safer and easier to read than code that includes lots of explicit typecasting, and the like.

They provide you with a great deal of power to write generic classes -- classes that basically behave the same, but use different types.

 

This page was last modified on 27 November, 2007