免费b2b网站大全免费黄页/seo课程总结
一 ,当我们new 一个HashMap
new HashMap();构造一个空的HashMap,使用默认的初始容量(16)和默认的负载因子(0.75)。负载因子的作用就是和扩容有关系
public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}
new HsahMap(10)构造一个具有指定初始容量和加载因子的空HashMap。但是实际上并不是10会去找比10大的2的次方数,也就是16
public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);}
/*** Returns a power of two size for the given target capacity.*/static final int tableSizeFor(int cap) {int n = cap - 1;n |= n >>> 1;n |= n >>> 2;n |= n >>> 4;n |= n >>> 8;n |= n >>> 16;return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;}
当我们put一对键值,首先对key进行一个hash操作获取到相应的hashCode
public V put(K key, V value) {return putVal(hash(key), key, value, false, true);}
static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//减少hash冲突,右移提高位数获取hash值的范围更官方可以理解}
putVal具体操作:wocao?什么代码?主要参数就是前三个,key与value我们都知道,hash什么作用呢
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {Node<K,V>[] tab; Node<K,V> p; int n, i;if ((tab = table) == null || (n = tab.length) == 0) //如果你使用的map为空n = (tab = resize()).length; //resize() -> 初始化数组大小(n,这里面限制了数组的长度必须是2的次方数)if ((p = tab[i = (n - 1) & hash]) == null)//开始存对象,这里与运算记住就是为了均匀的获取数组下标小算法(与:都是1结果为1否则为0)15:0000 1111 & 0000 0101 结果 0000 0101,所以下标取决于hash值,hash值是散列的比较均匀tab[i] = newNode(hash, key, value, null);//初始化一个node对象,根据hash值断定再数组中的下标else {//指的是放node冲突了Node<K,V> e; K k;if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))//比较key值是否相等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) {//直到找到最后一个节点,也就是.next == null 说明尾节点 1.7是头插法,1.8后是尾插法,为什么呢?因为1.8加了红黑树,所以需要知道节点的个数,所以使用尾插法遍历p.next = newNode(hash, key, value, null);if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);//binCount >= 7 链表有九个个节点转红黑树break;}if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}if (e != null) { // existing mapping for key key值存放做更新操作 onlyIfAbsend控制是否更新oldValueV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;if (++size > threshold)//threshold map大小 * 0.75resize();//扩容afterNodeInsertion(evict);return null;}
转红黑树
final void treeifyBin(Node<K,V>[] tab, int hash) {int n, index; Node<K,V> e;if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//转红黑树之前还要判断一下数组的长度,必须数组长度大于等于64链表节点个数大于8才会转红黑树resize();//不需要转红黑树,就把一个长链表转成两个短链表来提高效率(看下边)else if ((e = tab[index = (n - 1) & hash]) != null) {TreeNode<K,V> hd = null, tl = null;do {TreeNode<K,V> p = replacementTreeNode(e, null);if (tl == null)hd = p;else {p.prev = tl;tl.next = p;}tl = p;} while ((e = e.next) != null);if ((tab[index] = hd) != null)hd.treeify(tab);//这里才是去真正的转红黑树(一个红黑树有四个属性left right pre next是红黑树同时每三个节点已是一个双向链表) 先是单向链表转双向链表后再去转红黑树的(后续自己再扣下)}}
resize()扩容 — 整个hashMap一共有两个地方需要扩容,一个就是数组的长度,另一个就是链表的长度
final Node<K,V>[] resize() {Node<K,V>[] oldTab = table;int oldCap = (oldTab == null) ? 0 : oldTab.length;int oldThr = threshold;int newCap, newThr = 0;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 thresholdnewCap = oldThr;else { // zero initial threshold signifies using defaultsnewCap = 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;if (oldTab != null) {for (int j = 0; j < oldCap; ++j) {Node<K,V> e;if ((e = oldTab[j]) != null) {oldTab[j] = null;if (e.next == null)newTab[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);else { // preserve orderNode<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);if (loTail != null) {loTail.next = null;newTab[j] = loHead;}if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab;}
public static void main(String[] args) {HashMap<Object, Object> map = new HashMap<>(10);map.put("key","value");Object put = map.put("key", "value2");System.out.println(put); // -> 输出valueSystem.out.println(map.get("key")); // ->输出value2map.put("key2","value");Object put2 = map.putIfAbsent("key2", "value2");System.out.println(put2); // -> 输出valueSystem.out.println(map.get("key2")); // ->输出value}
解析
public V put(K key, V value) {return putVal(hash(key), key, value, false, true);//onlyIfAbsend = false 会覆盖}
public V putIfAbsent(K key, V value) {return putVal(hash(key), key, value, true, true); //onlyIfAbsend = false 不会覆盖}
思路