how to change the hashmap load factor

3.7k views Asked by At

We know that hashmap has default load factor 0.75, and if I want to change it how to do that.

Is there any method so that we can set and use the load factory. I have 100k records and I don't want to rehashing again and again, I want to change the load factor so that it can work efficiently without rehashing.

3

There are 3 answers

0
ΦXocę 웃 Пepeúpa ツ On BEST ANSWER

you can not change that after the map is created, the most you can y use the constructor defined for that

as the doc states:

public HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

 Map<String, String> x = new HashMap<>(10, 0.85f);
3
nagendra547 On

Following are 3 useful constructors to help you. Use it wisely :). More info here

HashMap()

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).


HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).


HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

As @Xoce mentioned, you can't change loadFactor later, I do agree with him on this. Use it while creating the hashmap.

@NPE has provided great details here about significance of loadfactor.

0
Sagar Kharab On

It's done at the time of constructing map. You can set the load factor and initial capacity. Initial capacity is the initial number of buckets for hashing and load factor is the maximum allowed percentage of entries before resizing and auto-increment. you can set the value as float.