hashfactor和hashmap的容量

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

Map m = new HashMap(10,1); //but after lots of works Here how to get current values. 

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

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

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

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