001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.collect.CollectPreconditions.checkNonnegative; 022import static com.google.common.collect.ObjectArrays.checkElementNotNull; 023 024import com.google.common.annotations.Beta; 025import com.google.common.annotations.GwtCompatible; 026import com.google.common.annotations.VisibleForTesting; 027import com.google.common.primitives.Ints; 028import com.google.errorprone.annotations.CanIgnoreReturnValue; 029import com.google.errorprone.annotations.concurrent.LazyInit; 030import com.google.j2objc.annotations.RetainedWith; 031import java.io.Serializable; 032import java.util.Arrays; 033import java.util.Collection; 034import java.util.Collections; 035import java.util.Iterator; 036import java.util.Set; 037import java.util.SortedSet; 038import org.checkerframework.checker.nullness.compatqual.NullableDecl; 039 040/** 041 * A {@link Set} whose contents will never change, with many other important properties detailed at 042 * {@link ImmutableCollection}. 043 * 044 * @since 2.0 045 */ 046@GwtCompatible(serializable = true, emulated = true) 047@SuppressWarnings("serial") // we're overriding default serialization 048public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> { 049 /** 050 * Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code 051 * consistency, and because the return type conveys the immutability guarantee. 052 */ 053 @SuppressWarnings({"unchecked"}) // fully variant implementation (never actually produces any Es) 054 public static <E> ImmutableSet<E> of() { 055 return (ImmutableSet<E>) RegularImmutableSet.EMPTY; 056 } 057 058 /** 059 * Returns an immutable set containing {@code element}. Preferred over {@link 060 * Collections#singleton} for code consistency, {@code null} rejection, and because the return 061 * type conveys the immutability guarantee. 062 */ 063 public static <E> ImmutableSet<E> of(E element) { 064 return new SingletonImmutableSet<E>(element); 065 } 066 067 /** 068 * Returns an immutable set containing the given elements, minus duplicates, in the order each was 069 * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except 070 * the first are ignored. 071 */ 072 public static <E> ImmutableSet<E> of(E e1, E e2) { 073 return construct(2, e1, e2); 074 } 075 076 /** 077 * Returns an immutable set containing the given elements, minus duplicates, in the order each was 078 * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except 079 * the first are ignored. 080 */ 081 public static <E> ImmutableSet<E> of(E e1, E e2, E e3) { 082 return construct(3, e1, e2, e3); 083 } 084 085 /** 086 * Returns an immutable set containing the given elements, minus duplicates, in the order each was 087 * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except 088 * the first are ignored. 089 */ 090 public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) { 091 return construct(4, e1, e2, e3, e4); 092 } 093 094 /** 095 * Returns an immutable set containing the given elements, minus duplicates, in the order each was 096 * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except 097 * the first are ignored. 098 */ 099 public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) { 100 return construct(5, e1, e2, e3, e4, e5); 101 } 102 103 /** 104 * Returns an immutable set containing the given elements, minus duplicates, in the order each was 105 * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except 106 * the first are ignored. 107 * 108 * @since 3.0 (source-compatible since 2.0) 109 */ 110 @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning. 111 public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { 112 final int paramCount = 6; 113 Object[] elements = new Object[paramCount + others.length]; 114 elements[0] = e1; 115 elements[1] = e2; 116 elements[2] = e3; 117 elements[3] = e4; 118 elements[4] = e5; 119 elements[5] = e6; 120 System.arraycopy(others, 0, elements, paramCount, others.length); 121 return construct(elements.length, elements); 122 } 123 124 /** 125 * Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array. If 126 * {@code k} is the size of the returned {@code ImmutableSet}, then the unique elements of {@code 127 * elements} will be in the first {@code k} positions, and {@code elements[i] == null} for {@code 128 * k <= i < n}. 129 * 130 * <p>After this method returns, {@code elements} will contain no duplicates, but {@code elements} 131 * may be the real array backing the returned set, so do not modify it further. 132 * 133 * <p>{@code elements} may contain only values of type {@code E}. 134 * 135 * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null 136 */ 137 private static <E> ImmutableSet<E> construct(int n, Object... elements) { 138 switch (n) { 139 case 0: 140 return of(); 141 case 1: 142 @SuppressWarnings("unchecked") // safe; elements contains only E's 143 E elem = (E) elements[0]; 144 return of(elem); 145 default: 146 // continue below to handle the general case 147 } 148 int tableSize = chooseTableSize(n); 149 Object[] table = new Object[tableSize]; 150 int mask = tableSize - 1; 151 int hashCode = 0; 152 int uniques = 0; 153 for (int i = 0; i < n; i++) { 154 Object element = checkElementNotNull(elements[i], i); 155 int hash = element.hashCode(); 156 for (int j = Hashing.smear(hash); ; j++) { 157 int index = j & mask; 158 Object value = table[index]; 159 if (value == null) { 160 // Came to an empty slot. Put the element here. 161 elements[uniques++] = element; 162 table[index] = element; 163 hashCode += hash; 164 break; 165 } else if (value.equals(element)) { 166 break; 167 } 168 } 169 } 170 Arrays.fill(elements, uniques, n, null); 171 if (uniques == 1) { 172 // There is only one element or elements are all duplicates 173 @SuppressWarnings("unchecked") // we are careful to only pass in E 174 E element = (E) elements[0]; 175 return new SingletonImmutableSet<E>(element, hashCode); 176 } else if (chooseTableSize(uniques) < tableSize / 2) { 177 // Resize the table when the array includes too many duplicates. 178 return construct(uniques, elements); 179 } else { 180 Object[] uniqueElements = 181 shouldTrim(uniques, elements.length) ? Arrays.copyOf(elements, uniques) : elements; 182 return new RegularImmutableSet<E>(uniqueElements, hashCode, table, mask, uniques); 183 } 184 } 185 186 private static boolean shouldTrim(int actualUnique, int expectedUnique) { 187 return actualUnique < (expectedUnique >> 1) + (expectedUnique >> 2); 188 } 189 190 // We use power-of-2 tables, and this is the highest int that's a power of 2 191 static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; 192 193 // Represents how tightly we can pack things, as a maximum. 194 private static final double DESIRED_LOAD_FACTOR = 0.7; 195 196 // If the set has this many elements, it will "max out" the table size 197 private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR); 198 199 /** 200 * Returns an array size suitable for the backing array of a hash table that uses open addressing 201 * with linear probing in its implementation. The returned size is the smallest power of two that 202 * can hold setSize elements with the desired load factor. Always returns at least setSize + 2. 203 */ 204 @VisibleForTesting 205 static int chooseTableSize(int setSize) { 206 setSize = Math.max(setSize, 2); 207 // Correct the size for open addressing to match desired load factor. 208 if (setSize < CUTOFF) { 209 // Round up to the next highest power of 2. 210 int tableSize = Integer.highestOneBit(setSize - 1) << 1; 211 while (tableSize * DESIRED_LOAD_FACTOR < setSize) { 212 tableSize <<= 1; 213 } 214 return tableSize; 215 } 216 217 // The table can't be completely full or we'll get infinite reprobes 218 checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); 219 return MAX_TABLE_SIZE; 220 } 221 222 /** 223 * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order 224 * each appears first in the source collection. 225 * 226 * <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation 227 * is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} will copy the data only once. 228 * This reduces the expense of habitually making defensive copies at API boundaries. However, the 229 * precise conditions for skipping the copy operation are undefined. 230 * 231 * @throws NullPointerException if any of {@code elements} is null 232 * @since 7.0 (source-compatible since 2.0) 233 */ 234 public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { 235 /* 236 * TODO(lowasser): consider checking for ImmutableAsList here 237 * TODO(lowasser): consider checking for Multiset here 238 */ 239 // Don't refer to ImmutableSortedSet by name so it won't pull in all that code 240 if (elements instanceof ImmutableSet && !(elements instanceof SortedSet)) { 241 @SuppressWarnings("unchecked") // all supported methods are covariant 242 ImmutableSet<E> set = (ImmutableSet<E>) elements; 243 if (!set.isPartialView()) { 244 return set; 245 } 246 } 247 Object[] array = elements.toArray(); 248 return construct(array.length, array); 249 } 250 251 /** 252 * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order 253 * each appears first in the source iterable. This method iterates over {@code elements} only 254 * once. 255 * 256 * <p><b>Performance note:</b> This method will sometimes recognize that the actual copy operation 257 * is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only 258 * once. This reduces the expense of habitually making defensive copies at API boundaries. 259 * However, the precise conditions for skipping the copy operation are undefined. 260 * 261 * @throws NullPointerException if any of {@code elements} is null 262 */ 263 public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) { 264 return (elements instanceof Collection) 265 ? copyOf((Collection<? extends E>) elements) 266 : copyOf(elements.iterator()); 267 } 268 269 /** 270 * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order 271 * each appears first in the source iterator. 272 * 273 * @throws NullPointerException if any of {@code elements} is null 274 */ 275 public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) { 276 // We special-case for 0 or 1 elements, but anything further is madness. 277 if (!elements.hasNext()) { 278 return of(); 279 } 280 E first = elements.next(); 281 if (!elements.hasNext()) { 282 return of(first); 283 } else { 284 return new ImmutableSet.Builder<E>().add(first).addAll(elements).build(); 285 } 286 } 287 288 /** 289 * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order 290 * each appears first in the source array. 291 * 292 * @throws NullPointerException if any of {@code elements} is null 293 * @since 3.0 294 */ 295 public static <E> ImmutableSet<E> copyOf(E[] elements) { 296 switch (elements.length) { 297 case 0: 298 return of(); 299 case 1: 300 return of(elements[0]); 301 default: 302 return construct(elements.length, elements.clone()); 303 } 304 } 305 306 ImmutableSet() {} 307 308 /** Returns {@code true} if the {@code hashCode()} method runs quickly. */ 309 boolean isHashCodeFast() { 310 return false; 311 } 312 313 @Override 314 public boolean equals(@NullableDecl Object object) { 315 if (object == this) { 316 return true; 317 } else if (object instanceof ImmutableSet 318 && isHashCodeFast() 319 && ((ImmutableSet<?>) object).isHashCodeFast() 320 && hashCode() != object.hashCode()) { 321 return false; 322 } 323 return Sets.equalsImpl(this, object); 324 } 325 326 @Override 327 public int hashCode() { 328 return Sets.hashCodeImpl(this); 329 } 330 331 // This declaration is needed to make Set.iterator() and 332 // ImmutableCollection.iterator() consistent. 333 @Override 334 public abstract UnmodifiableIterator<E> iterator(); 335 336 @LazyInit @NullableDecl @RetainedWith private transient ImmutableList<E> asList; 337 338 @Override 339 public ImmutableList<E> asList() { 340 ImmutableList<E> result = asList; 341 return (result == null) ? asList = createAsList() : result; 342 } 343 344 ImmutableList<E> createAsList() { 345 return ImmutableList.asImmutableList(toArray()); 346 } 347 348 abstract static class Indexed<E> extends ImmutableSet<E> { 349 abstract E get(int index); 350 351 @Override 352 public UnmodifiableIterator<E> iterator() { 353 return asList().iterator(); 354 } 355 356 @Override 357 ImmutableList<E> createAsList() { 358 return new ImmutableList<E>() { 359 @Override 360 public E get(int index) { 361 return Indexed.this.get(index); 362 } 363 364 @Override 365 boolean isPartialView() { 366 return Indexed.this.isPartialView(); 367 } 368 369 @Override 370 public int size() { 371 return Indexed.this.size(); 372 } 373 }; 374 } 375 } 376 377 /* 378 * This class is used to serialize all ImmutableSet instances, except for 379 * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It 380 * captures their "logical contents" and they are reconstructed using public 381 * static factories. This is necessary to ensure that the existence of a 382 * particular implementation type is an implementation detail. 383 */ 384 private static class SerializedForm implements Serializable { 385 final Object[] elements; 386 387 SerializedForm(Object[] elements) { 388 this.elements = elements; 389 } 390 391 Object readResolve() { 392 return copyOf(elements); 393 } 394 395 private static final long serialVersionUID = 0; 396 } 397 398 @Override 399 Object writeReplace() { 400 return new SerializedForm(toArray()); 401 } 402 403 /** 404 * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 405 * Builder} constructor. 406 */ 407 public static <E> Builder<E> builder() { 408 return new Builder<E>(); 409 } 410 411 /** 412 * Returns a new builder, expecting the specified number of distinct elements to be added. 413 * 414 * <p>If {@code expectedSize} is exactly the number of distinct elements added to the builder 415 * before {@link Builder#build} is called, the builder is likely to perform better than an unsized 416 * {@link #builder()} would have. 417 * 418 * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, 419 * but not exactly, the number of distinct elements added to the builder. 420 * 421 * @since 23.1 422 */ 423 @Beta 424 public static <E> Builder<E> builderWithExpectedSize(int expectedSize) { 425 checkNonnegative(expectedSize, "expectedSize"); 426 return new Builder<E>(expectedSize); 427 } 428 429 /** 430 * A builder for creating {@code ImmutableSet} instances. Example: 431 * 432 * <pre>{@code 433 * static final ImmutableSet<Color> GOOGLE_COLORS = 434 * ImmutableSet.<Color>builder() 435 * .addAll(WEBSAFE_COLORS) 436 * .add(new Color(0, 191, 255)) 437 * .build(); 438 * }</pre> 439 * 440 * <p>Elements appear in the resulting set in the same order they were first added to the builder. 441 * 442 * <p>Building does not change the state of the builder, so it is still possible to add more 443 * elements and to build again. 444 * 445 * @since 2.0 446 */ 447 public static class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> { 448 @NullableDecl @VisibleForTesting Object[] hashTable; 449 private int hashCode; 450 451 /** 452 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 453 * ImmutableSet#builder}. 454 */ 455 public Builder() { 456 super(DEFAULT_INITIAL_CAPACITY); 457 } 458 459 Builder(int capacity) { 460 super(capacity); 461 this.hashTable = new Object[chooseTableSize(capacity)]; 462 } 463 464 /** 465 * Adds {@code element} to the {@code ImmutableSet}. If the {@code ImmutableSet} already 466 * contains {@code element}, then {@code add} has no effect (only the previously added element 467 * is retained). 468 * 469 * @param element the element to add 470 * @return this {@code Builder} object 471 * @throws NullPointerException if {@code element} is null 472 */ 473 @CanIgnoreReturnValue 474 @Override 475 public Builder<E> add(E element) { 476 checkNotNull(element); 477 if (hashTable != null && chooseTableSize(size) <= hashTable.length) { 478 addDeduping(element); 479 return this; 480 } else { 481 hashTable = null; 482 super.add(element); 483 return this; 484 } 485 } 486 487 private void addDeduping(E element) { 488 int mask = hashTable.length - 1; 489 int hash = element.hashCode(); 490 for (int i = Hashing.smear(hash); ; i++) { 491 i &= mask; 492 Object previous = hashTable[i]; 493 if (previous == null) { 494 hashTable[i] = element; 495 hashCode += hash; 496 super.add(element); 497 return; 498 } else if (previous.equals(element)) { 499 return; 500 } 501 } 502 } 503 504 /** 505 * Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate 506 * elements (only the first duplicate element is added). 507 * 508 * @param elements the elements to add 509 * @return this {@code Builder} object 510 * @throws NullPointerException if {@code elements} is null or contains a null element 511 */ 512 @CanIgnoreReturnValue 513 @Override 514 public Builder<E> add(E... elements) { 515 if (hashTable != null) { 516 for (E e : elements) { 517 add(e); 518 } 519 } else { 520 super.add(elements); 521 } 522 return this; 523 } 524 525 /** 526 * Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate 527 * elements (only the first duplicate element is added). 528 * 529 * @param elements the {@code Iterable} to add to the {@code ImmutableSet} 530 * @return this {@code Builder} object 531 * @throws NullPointerException if {@code elements} is null or contains a null element 532 */ 533 @CanIgnoreReturnValue 534 @Override 535 public Builder<E> addAll(Iterable<? extends E> elements) { 536 checkNotNull(elements); 537 if (hashTable != null) { 538 for (E e : elements) { 539 add(e); 540 } 541 } else { 542 super.addAll(elements); 543 } 544 return this; 545 } 546 547 /** 548 * Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate 549 * elements (only the first duplicate element is added). 550 * 551 * @param elements the elements to add to the {@code ImmutableSet} 552 * @return this {@code Builder} object 553 * @throws NullPointerException if {@code elements} is null or contains a null element 554 */ 555 @CanIgnoreReturnValue 556 @Override 557 public Builder<E> addAll(Iterator<? extends E> elements) { 558 checkNotNull(elements); 559 while (elements.hasNext()) { 560 add(elements.next()); 561 } 562 return this; 563 } 564 565 /** 566 * Returns a newly-created {@code ImmutableSet} based on the contents of the {@code Builder}. 567 */ 568 @SuppressWarnings("unchecked") 569 @Override 570 public ImmutableSet<E> build() { 571 switch (size) { 572 case 0: 573 return of(); 574 case 1: 575 return (ImmutableSet<E>) of(contents[0]); 576 default: 577 ImmutableSet<E> result; 578 if (hashTable != null && chooseTableSize(size) == hashTable.length) { 579 Object[] uniqueElements = 580 shouldTrim(size, contents.length) ? Arrays.copyOf(contents, size) : contents; 581 result = 582 new RegularImmutableSet<E>( 583 uniqueElements, hashCode, hashTable, hashTable.length - 1, size); 584 } else { 585 result = construct(size, contents); 586 // construct has the side effect of deduping contents, so we update size 587 // accordingly. 588 size = result.size(); 589 } 590 forceCopy = true; 591 hashTable = null; 592 return result; 593 } 594 } 595 } 596}