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