Java HashMap Create newHashMap(final int size)

Here you can find the source of newHashMap(final int size)

Description

Returns a new HashMap initialized with a large enough capacity to allow adding size elements without causing a rehash.

License

Apache License

Parameter

Parameter Description
K type of the keys
V type of the values
size number of elements to accommodate without a rehash

Return

a new with a large enough capacity to accommodate size elements without a rehash

Declaration

public static <K, V> HashMap<K, V> newHashMap(final int size) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.HashMap;

public class Main {
    /**/*from  w  ww . j a va 2s  .  c om*/
     * Returns a new {@link HashMap} initialized with a large enough capacity to allow adding <code>size</code> elements without causing a rehash.
     * 
     * @param <K> type of the keys
     * @param <V> type of the values
     * @param size number of elements to accommodate without a rehash
     * @return a new {@link HashMap} with a large enough capacity to accommodate <code>size</code> elements without a rehash
     */
    public static <K, V> HashMap<K, V> newHashMap(final int size) {
        return new HashMap<>(hashCapacityForSize(size));
    }

    /**
     * Returns the minimal capacity of hash-based structures (e.g. {@link HashSet} or {@link HashMap}) calculated from the specified size (number of elements)
     * and the default load factor (which is 0.75).
     * 
     * @param size size to calculate the minimal capacity
     * @return the minimal capacity of hash-based structures for the specified size
     */
    public static int hashCapacityForSize(final int size) {
        return size * 4 / 3 + 1;
    }
}

Related

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