shiv
shiv

Reputation: 497

how to change the hashmap load factor

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.

Upvotes: 4

Views: 3985

Answers (3)

Sagar Kharab
Sagar Kharab

Reputation: 369

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.

Upvotes: 0

nagendra547
nagendra547

Reputation: 6302

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.

Upvotes: 0

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);

Upvotes: 3

Related Questions