1

Here is the decompiled java code the method that is used to put an entry in the a hash map.

/**
     * Implements Map.putAll and Map constructor.
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

Where does this formula come from and how does it work ?

float ft = ((float)s / loadFactor) + 1.0F;

and also what is the meant of this method

/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
    int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
Adelin
  • 18,144
  • 26
  • 115
  • 175
  • 1
    can you specify the java version, to check `tableSizeFor( cap )` - [HashMap](https://stackoverflow.com/a/48094803/5081877) – Yash Dec 10 '18 at 13:11

1 Answers1

2

currentSize should <= capacity * loadFactor, which means when currentSize / loadFactor > capacity, we should resize the map. The +1 is used for round up.

As it comments, tableSizeFor is used for:

Returns a power of two size for the given target capacity.

xingbin
  • 27,410
  • 9
  • 53
  • 103