Java HashMap Create newHashMap()

Here you can find the source of newHashMap()

Description

new Hash Map

License

Apache License

Declaration

public static <K, V> HashMap<K, V> newHashMap() 

Method Source Code

//package com.java2s;
/**//from   ww  w.j av a  2  s .  c  o m
 * Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */

import java.util.HashMap;

import java.util.Map;

public class Main {
    public static <K, V> HashMap<K, V> newHashMap() {
        return new HashMap<K, V>();
    }

    public static <K, V> HashMap<K, V> newHashMap(int size) {
        return new HashMap<K, V>(getInitialCapacityFromExpectedSize(size));
    }

    public static <K, V> HashMap<K, V> newHashMap(Map<K, V> map) {
        return new HashMap<K, V>(map);
    }

    /**
     * As the default loadFactor is of 0.75, we need to calculate the initial capacity from the expected size to avoid
     * resizing the collection when we populate the collection with all the initial elements. We use a calculation
     * similar to what is done in {@link HashMap#putAll(Map)}.
     *
     * @param expectedSize the expected size of the collection
     * @return the initial capacity of the collection
     */
    private static int getInitialCapacityFromExpectedSize(int expectedSize) {
        if (expectedSize < 3) {
            return expectedSize + 1;
        }
        return (int) ((float) expectedSize / 0.75f + 1.0f);
    }
}

Related

  1. newHashMap()
  2. newHashMap()
  3. newHashMap()
  4. newHashMap()
  5. newHashMap()
  6. newHashMap()
  7. newHashMap(final int initCapacity)
  8. newHashMap(final int size)
  9. newHashMap(final K key, final V value)