简体   繁体   中英

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM