Java Set Create asSet(T... ts)

Here you can find the source of asSet(T... ts)

Description

as Set

License

LGPL

Declaration

@SafeVarargs
    public static <T> Set<T> asSet(T... ts) 

Method Source Code

//package com.java2s;
/*/*from   w w w.j  a  v  a 2s  .co  m*/
 * Hibernate Search, full-text search for your domain model
 *
 * 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>.
 */

import java.util.Collections;

import java.util.HashSet;

import java.util.Set;

public class Main {
    @SafeVarargs
    public static <T> Set<T> asSet(T... ts) {
        Set<T> set = new HashSet<>(getInitialCapacityFromExpectedSize(ts.length));
        Collections.addAll(set, ts);
        return set;
    }

    /**
     * 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. asSet(T... element)
  2. asSet(T... elements)
  3. asSet(T... elements)
  4. asSet(T... elements)
  5. asSet(T... items)
  6. asSet(T... ts)
  7. asSet(T... values)
  8. asSet(T... values)
  9. toSet(Iterable things)