Java Glossary : generics

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : G words : generics.

generics
Gernerics are an advanced feature of Java 1.5. C++ has something similar called templates. You instantiate versions of classes using some type as a parameter, e.g. a stack of ints and or a stack of floats or a stack of objects. In most other languages from Sather to Ada, templating is called genericity or parameterised types.

All the Java Collection classes, e.g. HashMap, ArrayList, TreeList can contain only generic Objects. The problem with this is you must keep track manually what sorts of object are really in each Collection. The compiler won't warn you if you add a Cat to a Collection of Dogs.

Without genericity, in Java, you must, at run time, cast objects on the way into a Collection to make sure they are the right type, and cast them back again on the way out before you can use their methods. It is totally up to you as application programmer to enforce your rules about what sort of objects you want in each Collection. You can't simply declare that a Collection will contain only Dog objects, and have attempts put anything else in flagged at compile time.

Java 1.5 has generics implemented with high overhead, requiring implicit casts both on the way into the collection and on the way out. The compiler automatically casts all objects going into your collection to Dog, and will automatically cast them back to Dog on the way out. Inside the collection, they are treated as generic Objects.

In theory, neither of these two time consuming casts are necessary. However, removing them would create a vulnerability in the JVM that could be exploited maliciously. The saving grace of the design in that Sun did not need to change the JVM or class file structure to implement it.

You can try out the JDK 1.5 beta compiler with generics.

The Ugly

The syntax for generics is butt ugly. Here is a class that has two replaceable types D and C. D must implement both Comparable, and Serializable.

public class Kennel <D extends Comparable<D> & Serializable, C>

& is used where you would expect to use comma. extends is used where you would expect to use implements. < > is used where you would expect to use ( ). I can hardly believe Sun chose such disgusting inconsistent syntax. But that's what we are stuck with.

To avoid creating new keywords, generics recycles extends, super and & with meanings quite unrelated to the original meanings.

How To Use Generics

To create an ArrayList that can only hold Dog objects. If you attempt to put anything else in there, (except subclasses like Dalmatians), you will find out at compile time. This is a great improvement on the old days when you sometimes found out about your errors when you partly exercised the code at run time.

// create the ArrayList that can only contain Dogs.
ArrayList<Dog> dogs = new ArrayList<Dog>( 101 );

// add an element, will be implicitly checked to make sure it is a Dog
dogs.add( new Dog( "Bowser" ) );

// fetch an element, will be implicity cast back to Dog, no (Dog) necessary
Dog aDog = dogs. get( 0 );

This is all very well for container classes that treat their contents as simple Objects and never execute any methods on them. But what if you had a smart container that wanted to run some of the Dog methods on its contents? Then you would have to say something like this where D stands for the class of the variable type of the container. You define your new Kennel container that can only hold Dogs or their subclasses.

public class Kennel<D extends Dog>
   {

   /**
   * constructor
   */
   public Kennel ( int size )
      {
      ...
      }

   public void add ( D dog )
      {
      dog. bark(); ...
      }

   }

// Now you can now create a Kennel that only holds Dalmatians like this:
// The compiler will not let you create a Kennel of Objects
Kennel<Dalmatian> spottedDogs = new Kennel<Dalmatian>( 101 );

// If you try to add a Dog or an Object, the compiler will stop you.
spottedDogs.add ( new Dalmatian ( "Sparky" ));


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 923.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/generics.html J:\mindprod\jgloss\generics.html