Senior
What is load factor and how does it work?
sobes.tech AI
Answer from AI
Load factor in Java is a parameter that determines how full the hash table (e.g., HashMap) is before it is resized (rehash). It is expressed as the ratio of the number of elements to the size of the bucket array. For example, a load factor of 0.75 means that when the array is 75% full, it will be resized.
Here's how it works:
- When adding elements to a HashMap, if the number of elements exceeds the threshold = load factor * capacity, the array is resized (usually doubled).
- This helps balance memory usage and access speed: a smaller load factor reduces collisions but requires more memory; a larger one saves memory but increases collisions and search time.
Example:
HashMap<String, Integer> map = new HashMap<>(16, 0.75f);
// capacity = 16, load factor = 0.75
// threshold = 16 * 0.75 = 12
// When adding the 13th element, the array will be resized.