Given a map, determine the proper initial size for a new Map to hold the same number of values. - Java java.util

Java examples for java.util:Map Entry

Description

Given a map, determine the proper initial size for a new Map to hold the same number of values.

Demo Code

/*//from  w  w w .j a v  a 2  s  .com
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */
//package com.java2s;

import java.util.Map;
import java.util.Set;

public class Main {
    public static final int MINIMUM_INITIAL_CAPACITY = 16;
    public static final float LOAD_FACTOR = 0.75f;

    /**
     * Given a map, determine the proper initial size for a new Map to hold the same number of values.
     * Specifically we want to account for load size and load factor to prevent immediate resizing.
     *
     * @param original The original map
     *
     * @return The proper size.
     */
    public static int determineProperSizing(Map original) {
        return determineProperSizing(original.size());
    }

    /**
     * Given a set, determine the proper initial size for a new set to hold the same number of values.
     * Specifically we want to account for load size and load factor to prevent immediate resizing.
     *
     * @param original The original set
     *
     * @return The proper size.
     */
    public static int determineProperSizing(Set original) {
        return determineProperSizing(original.size());
    }

    /**
     * Determine the proper initial size for a new collection in order for it to hold the given a number of elements.
     * Specifically we want to account for load size and load factor to prevent immediate resizing.
     *
     * @param numberOfElements The number of elements to be stored.
     *
     * @return The proper size.
     */
    public static int determineProperSizing(int numberOfElements) {
        int actual = ((int) (numberOfElements / LOAD_FACTOR)) + 1;
        return Math.max(actual, MINIMUM_INITIAL_CAPACITY);
    }
}

Related Tutorials