Java examples for java.util:Set Operation
make Copy of a Set
/*//from ww w .j a v a 2 s. c om * 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.HashMap; import java.util.HashSet; 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; public static <T> Set<T> makeCopy(Set<T> source) { if (source == null) { return null; } final int size = source.size(); final Set<T> copy = new HashSet<T>(size + 1); copy.addAll(source); return copy; } public static <X, Y> Map<X, Y> makeCopy(Map<X, Y> map) { final Map<X, Y> copy = mapOfSize(map.size() + 1); copy.putAll(map); return copy; } /** * Build a properly sized map, especially handling load size and load factor to prevent immediate resizing. * <p/> * Especially helpful for copy map contents. * * @param size The size to make the map. * * @return The sized map. */ public static <K, V> Map<K, V> mapOfSize(int size) { return new HashMap<K, V>(determineProperSizing(size), LOAD_FACTOR); } /** * 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); } }