Limiting the max size of a HashMap in Java

后端 未结 6 1736
时光说笑
时光说笑 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 01:59

    You could create a new class like this to limit the size of a HashMap:

    public class MaxSizeHashMap extends LinkedHashMap {
        private final int maxSize;
    
        public MaxSizeHashMap(int maxSize) {
            this.maxSize = maxSize;
        }
    
        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > maxSize;
        }
    }
    

提交回复
热议问题