sunleo
sunleo

Reputation: 10943

Loadfactor and Capacity of hashmap

how to find the current load factor and Capacity of the hashmap?

Map m = new HashMap(10,1);

//but after lots of works

Here how to get current values.

Upvotes: 0

Views: 1818

Answers (2)

krishna2642
krishna2642

Reputation: 609

Load factor will remain constant. From the documentation:

 The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. 

By looking at the documentation we can say that:

1. loadFactor is always lessthan or equal to 1.

2. size of Map is always less than or equal to (capacity * loadFactor)

So we can find current capacity by writing a code snippet like this:

 public static Integer findCurrentMapCapacity(Map m, Integer initCapacity, Float loadFactor){
    //default values: initial capacity=16 and loadfactor=.75 
    if (initCapacity==null){
        initCapacity=16;
    }
    if(loadFactor==null){
        loadFactor=0.75f;
    }
    boolean capacityFound=false;
    Integer capacity=initCapacity;
    Integer size=m.size();
    while(!capacityFound){
        if(size>capacity*loadFactor){
            capacity=capacity*2;
        }else{
            capacityFound=true;
        }
    }
    return capacity;
}

Upvotes: 2

Joshua
Joshua

Reputation: 2479

You are not supposed to be able get the load factor and capacity; they are implementation details of the hashmap class. However, You can use reflection. Try to avoid using it though, it is generally a bad idea.

Field f1 = m.getClass().getDeclaredField("table");
f1.setAccessible(true);
int capacity = f1.get(m).length;

Field f2 = m.getClass().getDeclaredField("threshold");
f2.setAccessible(true);
int currentLoadFactor = f2.get(m);

Upvotes: 2

Related Questions