哈哈,关于hashTable的知识,还是以前背面试题,只是觉得hashTable不能存放null值,hashTable也是线程安全的,但是用的也少。那么来一探究竟,到底hashTable是啥。还是从常用的一些方法入手,并且分析一下hashTable和hashMap的区别。
1.无参构造函数
public Hashtable() { this(11, 0.75f);//数组初始长度是11,负载因子是0.75 }
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); }//可以看见,是在此时初始化数组的,而hashMap是在第一次put的时候才进行初始化。
2.put(key,value)
public synchronized V put(K key, V value) {//可以看见方法是synchronized的,那么就意味着hashTable是线程安全的 // Make sure the value is not null if (value == null) { //这里就能看见是不能存放null值的 throw new NullPointerException(); } //确保原本数组中 没有该元素 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) {//这里可以看出hashTable是基于链表的,并不存在树的结构 if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); //当不存在时,添加元素。 return null; }
继续进入addEntry方法
private void addEntry(int hash, K key, V value, int index) { modCount++;//修改次数++ Entry<?,?> tab[] = table; if (count >= threshold) { //count其实就可以看成hashMap的size,代表的是一共元素数量 //超过的话,就会进行rehash计算 rehash(); tab = table; hash = key.hashCode(); index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>) tab[index]; tab[index] = new Entry<>(hash, key, value, e);//这里是将新插入的元素插入到链头,而hashMap是插入到链尾(只是对比链表的情况) count++;//这个地方也是一个不同的地方,hashMap会在插入元素后也会去确认是否超容,而hashTable并不会 }
分为了两种情况
(1)不进行rehash
(2)进行rehash
第一种情况比较简单,就是单纯的插入。
第二种情况就需要先进行一次rehash(),其代码如下
protected void rehash() { int oldCapacity = table.length;//旧长度 Entry<?,?>[] oldMap = table;//旧数组 // overflow-conscious code int newCapacity = (oldCapacity << 1) + 1;//新容量 是 2倍+1 if (newCapacity - MAX_ARRAY_SIZE > 0) { if (oldCapacity == MAX_ARRAY_SIZE) // Keep running with MAX_ARRAY_SIZE buckets return; newCapacity = MAX_ARRAY_SIZE;//Integer.MAX_VALUE- 8 } 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; } } }