/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ publicHashMap(int initialCapacity, float loadFactor){ if (initialCapacity < 0) thrownew IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) thrownew IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); }
/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ publicHashMap(int initialCapacity){ this(initialCapacity, DEFAULT_LOAD_FACTOR); }
/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ publicHashMap(){ this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
/** * Constructs a new <tt>HashMap</tt> with the same mappings as the * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with * default load factor (0.75) and an initial capacity sufficient to * hold the mappings in the specified <tt>Map</tt>. * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ publicHashMap(Map<? extends K, ? extends V> m){ this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }
其中最主要的是初始化的大小 还有初始化填充因子 static final float DEFAULT_LOAD_FACTOR = 0.75f; HashMap的容量超过当前数组长度 X 加载因子,就会执行resize()算法 比如说向水桶中装水,此时HashMap就是一个桶, 这个桶的容量就是加载容量, 而加载因子就是你要控制向这个桶中倒的水不超过水桶容量的比例,比如加载因子是0.75 , 那么在装水的时候这个桶最多能装到3/4 处,超过这个比例时,桶会自动扩容。 因此,这个桶最多能装水 = 桶的容量 X 加载因子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * 获取初始值,你输入的初始值,不一定是初始化时所用的初始值。 * 为什么初始值必须是2得倍数呢,下面代码会给你解释。 * Returns a power of two size for the given target capacity. */ staticfinalinttableSizeFor(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; } MAXIMUM_CAPACITY = 1<<30;
/** * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds. */ staticfinalinthash(Object key){ int h; // 这一顿操作大概的意思就是保留了高16位的值 // 其实低16位得值也保留了下来,只要在做一次异或,值就变回来了 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value){ return putVal(hash(key), key, value, false, true); } /** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict){ Node<K,V>[] tab; Node<K,V> p; int n, i; // table未初始化或者长度为0,进行扩容 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 看下值放在哪一个table[] // 这里也有一个为什么table的大小为什么必须是2的倍数的原因 // n 是 tab的长度 那么 (n - 1) & hash 的意思就是? // 假如 长度为 16(10000) 那么 15(01111) & 就得到最后hash值相当于 h & (length - 1) == h % length // 这样数组也不会越界等 运算得比%运算得快 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); // 已经有了,就看下是放在 链表还是红黑树。 else { Node<K,V> e; K k; //先比较s是不是在头节点 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //或者是红黑树 elseif (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); //链表大于8个阈值直接转成红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //存在一模一样的key则跳出继续 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; // onlyIfAbsent为false或者旧值为null // onlyIfAbsent是传入的参数 默认w为false直接替换 if (!onlyIfAbsent || oldValue == null) //用新值替换旧值 e.value = value; afterNodeAccess(e); // 返回旧值 return oldValue; } } ++modCount; // 实际大小大于阈值则扩容 if (++size > threshold) resize(); afterNodeInsertion(evict); returnnull; }
/** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key){ Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
/** * Implements Map.get and related methods * * @param hash hash for key * @param key the key * @return the node, or null if none */ final Node<K,V> getNode(int hash, Object key){ Node<K,V>[] tab; Node<K,V> first, e; int n; K k; // table已经初始化,长度大于0,根据hash寻找table中的项也不为空 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //判断是不是第一个结点 是就返回 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; // 节点下面还有东西? if ((e = first.next) != null) { // 是红黑树吗? if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); //不是红黑树那你肯定是链表咯 do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } returnnull; }