Consider this HashMap extention (generates an instance of the V class when calling "get" if it's 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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.get(key);
}
}
The usage of it is something like this
Map<String,Section> sections = new HashMapSafe<String,Section>(Section.class);
sections.get(sectionName); //always returns a Section instance, existing or new
It seems to me redundant a little to supply "Section" twice, once as a generic type, and also supply it's class. I assume it's impossible, but is there to implement HashMapSafe, (keeping the same functionality) so it can be used like this?
Map<String,Section> sections = new HashMapSafe<String,Section>();
Or like this?:
Map<String,Section> sections = new HashMapSafe<String>(Section.class);