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