加载因子和hashmap的容量

时间:2013-11-14 03:15:49

标签: java

如何查找当前的加载因子和hashmap的容量?

Map m = new HashMap(10,1);

//but after lots of works

Here how to get current values.

2 个答案:

答案 0 :(得分:1)

你不应该能够获得负载系数和容量;它们是hashmap类的实现细节。但是,您可以使用反射。尽量避免使用它,但这通常是一个坏主意。

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

答案 1 :(得分:0)

负载系数将保持不变。来自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. 

通过查看文档我们可以说:

1。 loadFactor总是小于或等于1.

2。 Map的大小始终小于或等于(capacity * loadFactor)

因此,我们可以通过编写如下代码片段来找到当前容量:

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