How do I access nested HashMaps in Java?

后端 未结 10 786
再見小時候
再見小時候 2020-12-01 09:28

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

10条回答
  •  醉酒成梦
    2020-12-01 09:37

    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);
    

提交回复
热议问题