Java Map implementation that returns a default value instead of null

前端 未结 6 888
萌比男神i
萌比男神i 2020-12-14 06:27

I have a Map> in my code, where I\'d avoid potential null pointers if the map\'s #get() method returned an empty l

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 07:25

    Similar to previous posts except you can just override the get method if you want to change its behaviour.

    Map> map = new LinkedHashMap>() {
        public String get(Object key) {
            List list = super.get(key);
            if (list == null && key instanceof String)
               super.put(key, list = new ArrayList());
            return list;
        }
    }; 
    

提交回复
热议问题