Consider this HashMap extension (it generates an instance of class V when it calls "get" if it is null)
public class HashMapSafe<K, V> extends HashMap<K, V> implements Map<K, V>{ private Class<V> dataType; public HashMapSafe(Class<V> clazz){ dataType = clazz; } @SuppressWarnings("unchecked") @Override public V get(Object key) { if(!containsKey(key)){ try { put((K)key, dataType.newInstance()); } catch (InstantiationException e) {
Using this is something like this
Map<String,Section> sections = new HashMapSafe<String,Section>(Section.class); sections.get(sectionName);
It seems to me that I'm a little redundant to supply the "Section" twice, once as a generic type, and also supply it with a class. I suppose this is not possible, but is it possible to implement HashMapSafe (while maintaining the same functionality) so that it can be used like this?
Map<String,Section> sections = new HashMapSafe<String,Section>();
Or how is it ?:
Map<String,Section> sections = new HashMapSafe<String>(Section.class);
java generics
Eran medan
source share