View Javadoc
1   package com.github.davidmoten.guavamini;
2   
3   import java.util.Collection;
4   import java.util.Collections;
5   import java.util.HashSet;
6   import java.util.Iterator;
7   
8   import com.github.davidmoten.guavamini.annotations.VisibleForTesting;
9   
10  public final class Sets {
11  
12      private Sets() {
13          // prevent instantiation
14      }
15  
16      static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
17  
18      public static <E> HashSet<E> newHashSet(E... elements) {
19          Preconditions.checkNotNull(elements);
20          HashSet<E> set = newHashSetWithExpectedSize(elements.length);
21          Collections.addAll(set, elements);
22          return set;
23      }
24  
25      public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
26          return new HashSet<E>(capacity(expectedSize));
27      }
28  
29      /**
30       * Returns a capacity that is sufficient to keep the map from being resized
31       * as long as it grows no larger than expectedSize and the load factor is >=
32       * its default (0.75).
33       */
34      @VisibleForTesting
35      static int capacity(int expectedSize) {
36          if (expectedSize < 3) {
37              checkNonnegative(expectedSize, "expectedSize");
38              return expectedSize + 1;
39          }
40          if (expectedSize < MAX_POWER_OF_TWO) {
41              return expectedSize + expectedSize / 3;
42          }
43          return Integer.MAX_VALUE; // any large value
44      }
45  
46      @VisibleForTesting
47      static int checkNonnegative(int value, String name) {
48          if (value < 0) {
49              throw new IllegalArgumentException(name + " cannot be negative but was: " + value);
50          }
51          return value;
52      }
53  
54      public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
55          return (elements instanceof Collection) ? new HashSet<E>(Collections2.cast(elements))
56                  : newHashSet(elements.iterator());
57      }
58  
59      public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
60          HashSet<E> set = newHashSet();
61          Iterators.addAll(set, elements);
62          return set;
63      }
64  
65      public static <E> HashSet<E> newHashSet() {
66          return new HashSet<E>();
67      }
68  
69  }