Limiting the max size of a HashMap in Java

后端 未结 6 1751
时光说笑
时光说笑 2020-11-29 01:50

I want to limit the maximum size of a HashMap to take metrics on a variety of hashing algorithms that I\'m implementing. I looked at the loadfactor in one of

6条回答
  •  孤街浪徒
    2020-11-29 02:09

    Sometimes simpler is better.

    public class InstrumentedHashMap implements Map {
    
        private Map map;
    
        public InstrumentedHashMap() {
            map = new HashMap();
        }
    
        public boolean put(K key, V value) {
            if (map.size() >= MAX && !map.containsKey(key)) {
                 return false;
            } else {
                 map.put(key, value);
                 return true;
            }
        }
    
        ...
    }
    

提交回复
热议问题