Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

Why does Java HashMap need to increase or decrease when it can use chaining

If Java HashMap uses chaining to handle collisions why does it ever need to resize the hashtable for new keys to be added? As in what is the use of specifying the load factor as there is no need to increase or decrease the size of the HashTable from its initial capacity, right? For a fixed initial capacity the chains would just keep growing, won't they?

I understand it will increase the look up time to O(n) but I guess my question really is, HashMap must decide to double its size based on the length of the chain and not based on how full the hashtable is (also called load factor)?

question from:https://stackoverflow.com/questions/65924367/why-does-java-hashmap-need-to-increase-or-decrease-when-it-can-use-chaining

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...