考虑这个HashMap扩展(如果它为null,则在调用“get”时生成V类的实例)
- 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);
- }
- }
它的用法是这样的
- Map<String,Section> sections = new HashMapSafe<String,Section>(Section.class);
- sections.get(sectionName); //always returns a Section instance,existing or new
在我看来,两次提供“部分”一次多余,一次作为通用类型,并且还提供它的类.我认为这是不可能的,但是有没有实现HashMapSafe,(保持相同的功能)所以它可以像这样使用?
- Map<String,Section>();
或者像这样?:
- Map<String,Section> sections = new HashMapSafe<String>(Section.class);