I am reading Effective Java - Item 29. It talks about Heterogeneous container, in the example:
private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();
public <T> void putFavirite(Class<T> type, T insance) {
if(type == null) {
throw new NullPointerException();
}
favorites.put(type, insance);
....
}
This pattern parametrises the key instead of values, so you are not limited to a single type, unlike:
private Map<Integer, String> favorites ....
My question is: what if there are two elements of same type that needed to be added to the Map
, i.e. two String
, is this pattern still useful?
If you put two strings the second will override the first one. So it is useful only if this behaviour is desired. If you want to store more objects under the same key you can use other containers, for example :
Or you can use MultiMap from Guava : http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html
Or you can use MultiMap from apache commons : http://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/MultiMap.html