Java generic types for beginners

In a recent article, I introduced a class named Box. One strength of this class was that it could store any type of object (any subclass of Object) but this flexibility created inherent problems: the return type always had to be cast to the correct data type and the programmer–not the compiler–had to keep track of what type was stored in every box.

Here’s a reminder of the Box class and how it was used:

public class Box {
    private Object obj;
    public Box(Object obj) { this.obj = obj; }
    public Object get() { return obj; }
}

// In some other code...
Box myBox = new Box(new Integer(555));
Integer n1 = myBox.get(); // compilation error
Integer s = (String) myBox.get(); // run-time error
Integer n2 = (Integer) myBox.get(); // OK!

To address these problems we could create multiple classes (e.g. BoxInteger, BoxString, etc.) but this would be very labour intensive.

public interface Box {} 

// Yet another box class...
public class BoxFloat implements Box {
    private Float f;
    public BoxFloat(Float f) { this.f = f; }
    public Float get() { return f; }
}

Fortunately, Java offers a much better solution in the form of generic types which can look something like this:

public Box<T> {
// insert code hereĀ 
}

The updated class now has one formal type parameter, named “T”, that can be used as follows:

public class Box<T> {
    private T t;
    public Box(T t) { this.t = t; }
    public T get() { return t; }
}

The new generic version of the Box class is flexible and simple to use.

Box<Integer> b1; // generic type invocation
b1 = new Box<Integer>(new Integer(123));
Integer n1 = b1.get(); // no type casting!

Additionally, the compiler is now able to detect errors that might otherwise have occurred at run-time.

Box<String> sBox;
sBox = new Box<String>(new String("ABC"));
// Next line fails to compile
Integer n = sBox.get(); // incompatible types

That’s probably enough for one article, and if you would like to ask questions or suggest improvements, please use the comments form below.

One thought on “Java generic types for beginners

  1. Pingback: Generics in VB.Net « Reversing Entropy

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>