You're right, a HashMap does not need to dynamically resize. There is a constructor parameter, loadFactor
, that can be used to configure how aggressively HashMap resizes. You could in theory create a HashMap that never resizes like this:
Map<Integer, Integer> badMap = new HashMap<>(100, Float.POSITIVE_INFINITY);
But, as you have also noted, such a map would have O(n)
access time, as each "bucket" would grow proportional to the total size of the map. Therefore you shouldn't do this!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…