0

如何找到 hashmap 的当前负载因子和容量?

Map m = new HashMap(10,1);

//but after lots of works

Here how to get current values.
4

2 回答 2

2

您不应该能够获得负载系数和容量;它们是 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);
于 2013-11-14T03:42:28.393 回答
2

负载系数将保持不变。从 文档中:

 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的大小总是小于等于(容量* 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;
}
于 2013-11-14T04:40:09.507 回答