java1.8 hashtable源码学习

1、hashtable内部几个重要私有变量

/**
 * entries数组的计数器
 */
private transient int count;

 /**
 *
 * 阈值,hashtable entries数组容量扩充的阈值。该值是使用容量 * 加载因子计算得到的。
 * @serial
 */
private int threshold;


 /**
 * 加载因子
 *
 * @serial
 */
private float loadFactor;


 /**
 * hashtable entries被修改的次数加一些内部结构修改的次数。
 * 具体可以查看hashtable一些方法代码,里面会对该值进行加加操作。
 */
private transient int modCount = 0;

小结:加载因子和阈值的概念用于hashtable的扩充。

2、部分方法
默认构造方法:

/**
 * Constructs a new, empty hashtable with a default initial capacity (11)
 * and load factor (0.75).
 */
public Hashtable() {
    this(11, 0.75f);
}

 /**
 * Constructs a new, empty hashtable with the specified initial
 * capacity and the specified load factor.
 *
 * @param      initialCapacity   the initial capacity of the hashtable.
 * @param      loadFactor        the load factor of the hashtable.
 * @exception  IllegalArgumentException  if the initial capacity is less
 *             than zero, or if the load factor is nonpositive.
 */
public Hashtable(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal Load: "+loadFactor);

    if (initialCapacity==0)
        initialCapacity = 1;
    this.loadFactor = loadFactor;
    table = new Entry<?,?>[initialCapacity];
    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}

关键点说明:
initialCapacity 默认值为11
loadFactor 默认值为0.75

加载因子使用0.75 jdk给出了以下说明

  • Generally, the default load factor (.75) offers a good tradeoff between
  • time and space costs. Higher values decrease the space overhead but
  • increase the time cost to look up an entry (which is reflected in most
  • Hashtable operations, including get and put).

简单说0.75的加载因子是查询速度和占用空间的一个平衡点。(?0.75的依据)
初始容量使用11(初始容量与扩容算法和最大容量有关,详情见下文)

注意构造函数的这一行
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
说明了hashtable的最大阈值是MAX_ARRAY_SIZE + 1(为什么需要+1,是因为当前容量如果已经是数组最大值了,则再也不需要扩容。此时threshold使用MAX_ARRAY_SIZE + 1使现有容量永远达不到扩容阈值,从而避免扩容)
MAX_ARRAY_SIZE 的定义如下:

/**
 * The maximum size of array to allocate.
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * OutOfMemoryError: Requested array size exceeds VM limit
 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

数组作为一个对象,需要一定的内存存储对象头信息,对象头信息最大占用内存不可超过8字节。8*8=64bit,刚好是64位虚拟机不开启指针压缩情况下,markword的大小。

容量扩充:

/**
 * Increases the capacity of and internally reorganizes this
 * hashtable, in order to accommodate and access its entries more
 * efficiently.  This method is called automatically when the
 * number of keys in the hashtable exceeds this hashtable's capacity
 * and load factor.
 */
@SuppressWarnings("unchecked")
protected void rehash() {
    int oldCapacity = table.length;
    Entry<?,?>[] oldMap = table;

    // overflow-conscious code
    int newCapacity = (oldCapacity << 1) + 1;
    if (newCapacity - MAX_ARRAY_SIZE > 0) {
        if (oldCapacity == MAX_ARRAY_SIZE)
            // Keep running with MAX_ARRAY_SIZE buckets
            return;
        newCapacity = MAX_ARRAY_SIZE;
    }
    Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

    modCount++;
    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    table = newMap;

    for (int i = oldCapacity ; i-- > 0 ;) {
        for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
            Entry<K,V> e = old;
            old = old.next;

            int index = (e.hash & 0x7FFFFFFF) % newCapacity;
            e.next = (Entry<K,V>)newMap[index];
            newMap[index] = e;
        }
    }
}

扩容算法:
int newCapacity = (oldCapacity << 1) + 1;
新容量=旧容量*2+1 但不超过数组最大值。
hashtable初始容量为11,按照以上算法迭代计算

public class Main {

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

public static void main(String[] args) {
    int i = 11;
    for(;i < MAX_ARRAY_SIZE + 1 ;)
    {
        i = (i << 1) + 1;
    }
    System.out.println(i);
}

}
最终运行结果是:2147483647刚好是MAX_ARRAY_SIZE,也就是说初始容量为11按照扩容方法迭代计算才能使得hashtable的容量达到理论值的最大。

另外可以发现扩充容量的实质是重新分配一个entries数组,然后对原数组entries对象重新进行hash,hash算法也比较简单:
int index = (e.hash & 0x7FFFFFFF) % newCapacity;

经常看到hashtable key value不能为null,hashmap可以,现在从源码角度上来说明为什么不行。
put方法如下:

/**
 * Maps the specified <code>key</code> to the specified
 * <code>value</code> in this hashtable. Neither the key nor the
 * value can be <code>null</code>. <p>
 *
 * The value can be retrieved by calling the <code>get</code> method
 * with a key that is equal to the original key.
 *
 * @param      key     the hashtable key
 * @param      value   the value
 * @return     the previous value of the specified key in this hashtable,
 *             or <code>null</code> if it did not have one
 * @exception  NullPointerException  if the key or value is
 *               <code>null</code>
 * @see     Object#equals(Object)
 * @see     #get(Object)
 */
public synchronized V put(K key, V value) {
    // Make sure the value is not null
    if (value == null) {
        throw new NullPointerException();
    }

    // Makes sure the key is not already in the hashtable.
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> entry = (Entry<K,V>)tab[index];
    for(; entry != null ; entry = entry.next) {
        if ((entry.hash == hash) && entry.key.equals(key)) {
            V old = entry.value;
            entry.value = value;
            return old;
        }
    }

    addEntry(hash, key, value, index);
    return null;
}

可以看到hashtable的hash算法是需要获取对象的hash值的,此时主键如果为null,运行以下程序:

public class Main {

public static void main(String[] args) {
    String test = null;
    System.out.println(test.hashCode());
}

}

运行结果如下:
Exception in thread “main” java.lang.NullPointerException
at Main.main(Main.java:10)
所以主键不能为空。

博主原创,转载说明出处,O(∩_∩)O谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值