I have a HashMap in Java, the contents of which (as you all probably know) can be accessed by
HashMap.get(\"keyname\");
If a have a HashMap
I prefer creating a custom map that extends HashMap. Then just override get() to add extra logic so that if the map doesnt contain your key. It will a create a new instance of the nested map, add it, then return it.
public class KMap extends HashMap {
public KMap() {
super();
}
@Override
public V get(Object key) {
if (this.containsKey(key)) {
return super.get(key);
} else {
Map value = new KMap();
super.put((K)key, (V)value);
return (V)value;
}
}
}
Now you can use it like so:
Map>> nestedMap = new KMap>>();
Map map = (Map) nestedMap.get(1).get(2);
Object obj= new Object();
map.put(someKey, obj);