Generics and Parameters of Type Class

[2005-08-07] dev, java
(Ad, please don’t block)

Warning (2022-08-14): This page got mangled years ago and I just tried to restore it. I forgot most of what I knew about Java, so this code may contain syntax errors.


Generics allow parameters to determine the type of the return value. This can be used to avoid a cast when returning objects from an internal map, by using the class of the object as a key.

Note that put() also enforces the type of the value, at compile time.

public class TypedMap {
  private Map<Class<?>, ?> _data = new HashMap();
  public <T> T get(Class<T> key) {
    return key.cast(_data.get(key));
  }
  public <T> void put(Class<T> key, T value) {
    _data.put(key, value);
  }
  public static void main(String[] args) {
    TypedMap typedMap = new TypedMap();
    typedMap.put(Integer.class, new Integer(3)); // could also auto-box here
    Integer myInt = typedMap.get(Integer.class); // could also auto-unbox here
  }
}

If you need several keys whose value has the same class, you can extend the above idea as follows. If you want different keys with the same content to point to the same value, you'll have to implement equals() and hashCode(), though.

public class TypedMap2 {
  public static class Key<T> {
    public String id;
    public Class<T> contentType;
    protected Key(String myID, Class<T> myContentType) {
      id = myID;
      contentType = myContentType;
    }
  }
  /** pre-defined keys */
  public static final Key<integer> INT_KEY = new Key("intKey", Integer.class);
   
  private Map<Key<?>,?> _data = new HashMap();
  public <T> T get(Key<T> key) {
    return key.contentType.cast(_data.get(key));
  }
  public <T> void put(Key<T> key, T value) {
    _data.put(key, value);
  }
  public static void main(String[] args) {
    TypedMap2 typedMap = new TypedMap2();
    typedMap.put(INT_KEY, new Integer(3)); // could also auto-box here
    Integer myInt = typedMap.get(INT_KEY); // could also auto-unbox here
  }
}