Constructs an ImmutableSet from the first n elements of the specified array. If k is the size of the returned ImmutableSet, then the unique elements of elements will be in the first k positions, and elements[i] == null for k <= i < n.
(int n, Object... elements)
| 134 | * null |
| 135 | */ |
| 136 | private static <E> ImmutableSet<E> construct(int n, Object... elements) { |
| 137 | switch (n) { |
| 138 | case 0: |
| 139 | return of(); |
| 140 | case 1: |
| 141 | @SuppressWarnings("unchecked") // safe; elements contains only E's |
| 142 | E elem = (E) elements[0]; |
| 143 | return of(elem); |
| 144 | default: |
| 145 | // continue below to handle the general case |
| 146 | } |
| 147 | int tableSize = chooseTableSize(n); |
| 148 | Object[] table = new Object[tableSize]; |
| 149 | int mask = tableSize - 1; |
| 150 | int hashCode = 0; |
| 151 | int uniques = 0; |
| 152 | for (int i = 0; i < n; i++) { |
| 153 | Object element = checkElementNotNull(elements[i], i); |
| 154 | int hash = element.hashCode(); |
| 155 | for (int j = Hashing.smear(hash); ; j++) { |
| 156 | int index = j & mask; |
| 157 | Object value = table[index]; |
| 158 | if (value == null) { |
| 159 | // Came to an empty slot. Put the element here. |
| 160 | elements[uniques++] = element; |
| 161 | table[index] = element; |
| 162 | hashCode += hash; |
| 163 | break; |
| 164 | } else if (value.equals(element)) { |
| 165 | break; |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | Arrays.fill(elements, uniques, n, null); |
| 170 | if (uniques == 1) { |
| 171 | // There is only one element or elements are all duplicates |
| 172 | @SuppressWarnings("unchecked") // we are careful to only pass in E |
| 173 | E element = (E) elements[0]; |
| 174 | return new SingletonImmutableSet<E>(element, hashCode); |
| 175 | } else if (tableSize != chooseTableSize(uniques)) { |
| 176 | // Resize the table when the array includes too many duplicates. |
| 177 | // when this happens, we have already made a copy |
| 178 | return construct(uniques, elements); |
| 179 | } else { |
| 180 | Object[] uniqueElements = |
| 181 | (uniques < elements.length) ? ObjectArrays.arraysCopyOf(elements, uniques) : elements; |
| 182 | return new RegularImmutableSet<E>(uniqueElements, hashCode, table, mask); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // We use power-of-2 tables, and this is the highest int that's a power of 2 |
| 187 | static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; |
no test coverage detected