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 {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
private Map_data = new HashMap ();
publicT get(Class key) {
return key.cast(_data.get(key));
}
publicvoid put(Class 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
}
}
equals()
and hashCode()
, though.public class TypedMap2 {
public static class Key{
public String id;
public ClasscontentType;
protected Key(String myID, ClassmyContentType) {
id = myID;
contentType = myContentType;
}
}
/** pre-defined keys */
public static final KeyINT_KEY = new Key("intKey", Integer.class);
private Map_data = new HashMap ();
publicT get(Key key) {
return key.contentType.cast(_data.get(key));
}
publicvoid put(Key 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
}
}