68 java集合和泛型_18 _HashMap与HashTable的区别

文章目录??HashMap????HashTable????HashMap与HashTable的区别??HashMap线程不安全底层实现:数组+链表或者红黑树Node节点的定义(链表)初始容量为16的原因put方法//底层实现:数组+链表或者红黑树//保存的数组,初始化16个transient Node<K,V>[] table;//为entrySet和value提供一个缓存transient Set<Map.Entry<K,V>> entrySet;//元素的数量transient int size;//初始容量static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16//最大容量static final int MAXIMUM_CAPACITY = 1 << 30;//数组递增的策略 当size > capacity*loadFacotor的时候递增final float loadFactor;//Node节点的定义(链表)static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next;}//初始容量为16的原因//hash算法,保证哈希值平均分布,只有当为16的时候才可以最大程度的保证平均分布static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);} //put方法//创建一个HashMap对象,并且设定它的加载因子为0.75(超过则扩容,)public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}static final float DEFAULT_LOAD_FACTOR = 0.75f;//执行put方法public V put(K key, V value) { //key通过hash算法计算一个index return putVal(hash(key), key, value, false, true);}final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //第一次进入为null,所以执行初始化容器大小 if ((tab = table) == null || (n = tab.length) == 0) //此时返回的就是初始化容器以后的大小即16 n = (tab = resize()).length; //计算下标,如果等于null,直接赋值 if ((p = tab[i = (n – 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { //如果该数组刚好有值,则采用链表或者红黑树的方式添加数据节点 Node<K,V> e; K k; //判断两个节点是否相等 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //判断当前节点是否属于红黑树节点 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //如果不是直接进行链表连接 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { //将当前节点的下一个节点设置为新的实体节点 p.next = newNode(hash, key, value, null); //如果此时的节点容量为7那么将链表转换为红黑树 if (binCount >= TREEIFY_THRESHOLD – 1) // -1 for 1st treeifyBin(tab, hash); break; } //判断新传入的实体和当前绑定节点的子节点是否相同,如果相同直接退出 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; //进入这个子节点 p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } //修改次数 ++modCount; //查看当前容器的容量是否大于threshold ,如果大于增加数组容量为原来的一倍 if (++size > threshold) resize(); afterNodeInsertion(evict); return null;} //初始化容器大小final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; //旧容量为0 int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; //设置当前容器的递增为0 int newCap, newThr = 0; //此时的oldCap=0 , newThr = 0 直接else执行 if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } //扩容,将数组的容量和扩容因子变为原来的一倍 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults //初始化容器为默认16 newCap = DEFAULT_INITIAL_CAPACITY; //初始化阙值 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({“rawtypes”,”unchecked”}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; //初始化存储容器数组 table = newTab;}HashTableHashTable也是基于哈希表实现,和HashMap不同的是HashTable是线程安全的。底层实现:哈希表+链表Hash函数初始化。在构造方法中初始化。初始化指为11put方法//底层实现:哈希表+链表private transient Entry<?,?>[] table;//存储数组private transient int count;//容器中数据多少private int threshold;//容器容量达到次数以后进行修改private transient int modCount = 0;//修改次数//Hash函数 int hash = key.hashCode(); //在这两行 int index = (hash & 0x7FFFFFFF) % tab.length; //在这两行 //初始化。在构造方法中初始化。初始化指为11public 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);}//put方法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; //hash函数计算一个index 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; }//增加实体private void addEntry(int hash, K key, V value, int index) { Entry<?,?> tab[] = table; if (count >= threshold) { // Rehash the table if the threshold is exceeded 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); count++; modCount++; }HashMap与HashTable的区别

对比项

HashTable

HashMap

底层时间

哈希表+链表

哈希表+链表+红黑树

初始化时间及大小

构造方法初始化,大小为11

put方法初始化,大小为16

线程安全

安全

不安全

Hash值

直接使用了hashcode

重新计算

扩容

二倍+1

二倍

山不厌高,水不厌深。

68 java集合和泛型_18 _HashMap与HashTable的区别

相关文章:

你感兴趣的文章:

标签云: