Generics

Problem

Some methods are type-independent. They don't care about the type of data they process. Never the less, an overly-strict type checker requires us to declare distinct methods, one for each type of data processed.

For example:

class StringNode {
   String data;
   public String getData() {
      return data;
   }
   public void setData(String newData) {
      data = newData;
   }
   // etc.
}

class IntegerNode {
   Integer data;
   public Integer getData() {
      return data;
   }
   public void setData(Integer newData) {
      data = newData;
   }
   // etc.
}

We can get around this by declaring a single method that processes objects:

class Node {
   Object data;
   public Object getData() {
      return data;
   }
   public void setData(Object newData) {
      data = newData;
   }
   // etc.
}

This works, but now the type checking isn't strict enough:

Node node = new Node();
node.setData("Beatles");
String band = (String)node.getData();
node.setData(new Integer(42));
String band = (String)node.getData(); // runtime cast error not compile time type error

Solution

Later versions of Java allow class and method declarations to be parameterized by types:

class Node<Data> {
   Data data;
   public Data getData() {
      return data;
   }
   public void setData(Data newData) {
      data = newData;
   }
   // etc.
}

We must specify the value of Data at the time a node is declared:

Node<String> node = new Node<String>();
node.setData("Beatles");
String band = node.getData(); // note: no cast necessary
node.setData(new Integer(42)); // compile time type error