001/* 002 * Copyright (C) 2008 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.checkNotNull; 020import static com.google.common.collect.CollectPreconditions.checkNonnegative; 021import static com.google.common.collect.ObjectArrays.checkElementsNotNull; 022 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.J2ktIncompatible; 025import com.google.errorprone.annotations.CanIgnoreReturnValue; 026import com.google.errorprone.annotations.DoNotCall; 027import com.google.errorprone.annotations.DoNotMock; 028import java.io.InvalidObjectException; 029import java.io.ObjectInputStream; 030import java.io.Serializable; 031import java.util.AbstractCollection; 032import java.util.Arrays; 033import java.util.Collection; 034import java.util.Collections; 035import java.util.HashSet; 036import java.util.Iterator; 037import java.util.List; 038import javax.annotation.CheckForNull; 039import org.checkerframework.checker.nullness.qual.Nullable; 040 041/** 042 * A {@link Collection} whose contents will never change, and which offers a few additional 043 * guarantees detailed below. 044 * 045 * <p><b>Warning:</b> avoid <i>direct</i> usage of {@link ImmutableCollection} as a type (just as 046 * with {@link Collection} itself). Prefer subtypes such as {@link ImmutableSet} or {@link 047 * ImmutableList}, which have well-defined {@link #equals} semantics, thus avoiding a common source 048 * of bugs and confusion. 049 * 050 * <h3>About <i>all</i> {@code Immutable-} collections</h3> 051 * 052 * <p>The remainder of this documentation applies to every public {@code Immutable-} type in this 053 * package, whether it is a subtype of {@code ImmutableCollection} or not. 054 * 055 * <h4>Guarantees</h4> 056 * 057 * <p>Each makes the following guarantees: 058 * 059 * <ul> 060 * <li><b>Shallow immutability.</b> Elements can never be added, removed or replaced in this 061 * collection. This is a stronger guarantee than that of {@link 062 * Collections#unmodifiableCollection}, whose contents change whenever the wrapped collection 063 * is modified. 064 * <li><b>Null-hostility.</b> This collection will never contain a null element. 065 * <li><b>Deterministic iteration.</b> The iteration order is always well-defined, depending on 066 * how the collection was created. Typically this is insertion order unless an explicit 067 * ordering is otherwise specified (e.g. {@link ImmutableSortedSet#naturalOrder}). See the 068 * appropriate factory method for details. View collections such as {@link 069 * ImmutableMultiset#elementSet} iterate in the same order as the parent, except as noted. 070 * <li><b>Thread safety.</b> It is safe to access this collection concurrently from multiple 071 * threads. 072 * <li><b>Integrity.</b> This type cannot be subclassed outside this package (which would allow 073 * these guarantees to be violated). 074 * </ul> 075 * 076 * <h4>"Interfaces", not implementations</h4> 077 * 078 * <p>These are classes instead of interfaces to prevent external subtyping, but should be thought 079 * of as interfaces in every important sense. Each public class such as {@link ImmutableSet} is a 080 * <i>type</i> offering meaningful behavioral guarantees. This is substantially different from the 081 * case of (say) {@link HashSet}, which is an <i>implementation</i>, with semantics that were 082 * largely defined by its supertype. 083 * 084 * <p>For field types and method return types, you should generally use the immutable type (such as 085 * {@link ImmutableList}) instead of the general collection interface type (such as {@link List}). 086 * This communicates to your callers all of the semantic guarantees listed above, which is almost 087 * always very useful information. 088 * 089 * <p>On the other hand, a <i>parameter</i> type of {@link ImmutableList} is generally a nuisance to 090 * callers. Instead, accept {@link Iterable} and have your method or constructor body pass it to the 091 * appropriate {@code copyOf} method itself. 092 * 093 * <p>Expressing the immutability guarantee directly in the type that user code references is a 094 * powerful advantage. Although Java offers certain immutable collection factory methods, such as 095 * {@link Collections#singleton(Object)} and <a 096 * href="https://docs.oracle.com/javase/9/docs/api/java/util/Set.html#immutable">{@code Set.of}</a>, 097 * we recommend using <i>these</i> classes instead for this reason (as well as for consistency). 098 * 099 * <h4>Creation</h4> 100 * 101 * <p>Except for logically "abstract" types like {@code ImmutableCollection} itself, each {@code 102 * Immutable} type provides the static operations you need to obtain instances of that type. These 103 * usually include: 104 * 105 * <ul> 106 * <li>Static methods named {@code of}, accepting an explicit list of elements or entries. 107 * <li>Static methods named {@code copyOf} (or {@code copyOfSorted}), accepting an existing 108 * collection whose contents should be copied. 109 * <li>A static nested {@code Builder} class which can be used to populate a new immutable 110 * instance. 111 * </ul> 112 * 113 * <h4>Warnings</h4> 114 * 115 * <ul> 116 * <li><b>Warning:</b> as with any collection, it is almost always a bad idea to modify an element 117 * (in a way that affects its {@link Object#equals} behavior) while it is contained in a 118 * collection. Undefined behavior and bugs will result. It's generally best to avoid using 119 * mutable objects as elements at all, as many users may expect your "immutable" object to be 120 * <i>deeply</i> immutable. 121 * </ul> 122 * 123 * <h4>Performance notes</h4> 124 * 125 * <ul> 126 * <li>Implementations can be generally assumed to prioritize memory efficiency, then speed of 127 * access, and lastly speed of creation. 128 * <li>The {@code copyOf} methods will sometimes recognize that the actual copy operation is 129 * unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only 130 * once. This reduces the expense of habitually making defensive copies at API boundaries. 131 * However, the precise conditions for skipping the copy operation are undefined. 132 * <li><b>Warning:</b> a view collection such as {@link ImmutableMap#keySet} or {@link 133 * ImmutableList#subList} may retain a reference to the entire data set, preventing it from 134 * being garbage collected. If some of the data is no longer reachable through other means, 135 * this constitutes a memory leak. Pass the view collection to the appropriate {@code copyOf} 136 * method to obtain a correctly-sized copy. 137 * <li>The performance of using the associated {@code Builder} class can be assumed to be no 138 * worse, and possibly better, than creating a mutable collection and copying it. 139 * <li>Implementations generally do not cache hash codes. If your element or key type has a slow 140 * {@code hashCode} implementation, it should cache it itself. 141 * </ul> 142 * 143 * <h4>Example usage</h4> 144 * 145 * <pre>{@code 146 * class Foo { 147 * private static final ImmutableSet<String> RESERVED_CODES = 148 * ImmutableSet.of("AZ", "CQ", "ZX"); 149 * 150 * private final ImmutableSet<String> codes; 151 * 152 * public Foo(Iterable<String> codes) { 153 * this.codes = ImmutableSet.copyOf(codes); 154 * checkArgument(Collections.disjoint(this.codes, RESERVED_CODES)); 155 * } 156 * } 157 * }</pre> 158 * 159 * <h3>See also</h3> 160 * 161 * <p>See the Guava User Guide article on <a href= 162 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>. 163 * 164 * @since 2.0 165 */ 166@DoNotMock("Use ImmutableList.of or another implementation") 167@GwtCompatible(emulated = true) 168@SuppressWarnings("serial") // we're overriding default serialization 169@ElementTypesAreNonnullByDefault 170// TODO(kevinb): I think we should push everything down to "BaseImmutableCollection" or something, 171// just to do everything we can to emphasize the "practically an interface" nature of this class. 172public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable { 173 174 ImmutableCollection() {} 175 176 /** Returns an unmodifiable iterator across the elements in this collection. */ 177 @Override 178 public abstract UnmodifiableIterator<E> iterator(); 179 180 private static final Object[] EMPTY_ARRAY = {}; 181 182 @Override 183 @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation 184 public final Object[] toArray() { 185 return toArray(EMPTY_ARRAY); 186 } 187 188 @CanIgnoreReturnValue 189 @Override 190 /* 191 * This suppression is here for two reasons: 192 * 193 * 1. b/192354773 in our checker affects toArray declarations. 194 * 195 * 2. `other[size] = null` is unsound. We could "fix" this by requiring callers to pass in an 196 * array with a nullable element type. But probably they usually want an array with a non-nullable 197 * type. That said, we could *accept* a `@Nullable T[]` (which, given that we treat arrays as 198 * covariant, would still permit a plain `T[]`) and return a plain `T[]`. But of course that would 199 * require its own suppression, since it is also unsound. toArray(T[]) is just a mess from a 200 * nullness perspective. The signature below at least has the virtue of being relatively simple. 201 */ 202 @SuppressWarnings("nullness") 203 public final <T extends @Nullable Object> T[] toArray(T[] other) { 204 checkNotNull(other); 205 int size = size(); 206 207 if (other.length < size) { 208 Object[] internal = internalArray(); 209 if (internal != null) { 210 return Platform.copy(internal, internalArrayStart(), internalArrayEnd(), other); 211 } 212 other = ObjectArrays.newArray(other, size); 213 } else if (other.length > size) { 214 other[size] = null; 215 } 216 copyIntoArray(other, 0); 217 return other; 218 } 219 220 /** If this collection is backed by an array of its elements in insertion order, returns it. */ 221 @CheckForNull 222 @Nullable 223 Object[] internalArray() { 224 return null; 225 } 226 227 /** 228 * If this collection is backed by an array of its elements in insertion order, returns the offset 229 * where this collection's elements start. 230 */ 231 int internalArrayStart() { 232 throw new UnsupportedOperationException(); 233 } 234 235 /** 236 * If this collection is backed by an array of its elements in insertion order, returns the offset 237 * where this collection's elements end. 238 */ 239 int internalArrayEnd() { 240 throw new UnsupportedOperationException(); 241 } 242 243 @Override 244 public abstract boolean contains(@CheckForNull Object object); 245 246 /** 247 * Guaranteed to throw an exception and leave the collection unmodified. 248 * 249 * @throws UnsupportedOperationException always 250 * @deprecated Unsupported operation. 251 */ 252 @CanIgnoreReturnValue 253 @Deprecated 254 @Override 255 @DoNotCall("Always throws UnsupportedOperationException") 256 public final boolean add(E e) { 257 throw new UnsupportedOperationException(); 258 } 259 260 /** 261 * Guaranteed to throw an exception and leave the collection unmodified. 262 * 263 * @throws UnsupportedOperationException always 264 * @deprecated Unsupported operation. 265 */ 266 @CanIgnoreReturnValue 267 @Deprecated 268 @Override 269 @DoNotCall("Always throws UnsupportedOperationException") 270 public final boolean remove(@CheckForNull Object object) { 271 throw new UnsupportedOperationException(); 272 } 273 274 /** 275 * Guaranteed to throw an exception and leave the collection unmodified. 276 * 277 * @throws UnsupportedOperationException always 278 * @deprecated Unsupported operation. 279 */ 280 @CanIgnoreReturnValue 281 @Deprecated 282 @Override 283 @DoNotCall("Always throws UnsupportedOperationException") 284 public final boolean addAll(Collection<? extends E> newElements) { 285 throw new UnsupportedOperationException(); 286 } 287 288 /** 289 * Guaranteed to throw an exception and leave the collection unmodified. 290 * 291 * @throws UnsupportedOperationException always 292 * @deprecated Unsupported operation. 293 */ 294 @CanIgnoreReturnValue 295 @Deprecated 296 @Override 297 @DoNotCall("Always throws UnsupportedOperationException") 298 public final boolean removeAll(Collection<?> oldElements) { 299 throw new UnsupportedOperationException(); 300 } 301 302 /** 303 * Guaranteed to throw an exception and leave the collection unmodified. 304 * 305 * @throws UnsupportedOperationException always 306 * @deprecated Unsupported operation. 307 */ 308 @CanIgnoreReturnValue 309 @Deprecated 310 @Override 311 @DoNotCall("Always throws UnsupportedOperationException") 312 public final boolean retainAll(Collection<?> elementsToKeep) { 313 throw new UnsupportedOperationException(); 314 } 315 316 /** 317 * Guaranteed to throw an exception and leave the collection unmodified. 318 * 319 * @throws UnsupportedOperationException always 320 * @deprecated Unsupported operation. 321 */ 322 @Deprecated 323 @Override 324 @DoNotCall("Always throws UnsupportedOperationException") 325 public final void clear() { 326 throw new UnsupportedOperationException(); 327 } 328 329 /** 330 * Returns an {@code ImmutableList} containing the same elements, in the same order, as this 331 * collection. 332 * 333 * <p><b>Performance note:</b> in most cases this method can return quickly without actually 334 * copying anything. The exact circumstances under which the copy is performed are undefined and 335 * subject to change. 336 * 337 * @since 2.0 338 */ 339 public ImmutableList<E> asList() { 340 return isEmpty() ? ImmutableList.<E>of() : ImmutableList.<E>asImmutableList(toArray()); 341 } 342 343 /** 344 * Returns {@code true} if this immutable collection's implementation contains references to 345 * user-created objects that aren't accessible via this collection's methods. This is generally 346 * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid 347 * memory leaks. 348 */ 349 abstract boolean isPartialView(); 350 351 /** 352 * Copies the contents of this immutable collection into the specified array at the specified 353 * offset. Returns {@code offset + size()}. 354 */ 355 @CanIgnoreReturnValue 356 int copyIntoArray(@Nullable Object[] dst, int offset) { 357 for (E e : this) { 358 dst[offset++] = e; 359 } 360 return offset; 361 } 362 363 @J2ktIncompatible // serialization 364 Object writeReplace() { 365 // We serialize by default to ImmutableList, the simplest thing that works. 366 return new ImmutableList.SerializedForm(toArray()); 367 } 368 369 @J2ktIncompatible // serialization 370 private void readObject(ObjectInputStream stream) throws InvalidObjectException { 371 throw new InvalidObjectException("Use SerializedForm"); 372 } 373 374 /** 375 * Abstract base class for builders of {@link ImmutableCollection} types. 376 * 377 * @since 10.0 378 */ 379 @DoNotMock 380 public abstract static class Builder<E> { 381 static final int DEFAULT_INITIAL_CAPACITY = 4; 382 383 static int expandedCapacity(int oldCapacity, int minCapacity) { 384 if (minCapacity < 0) { 385 throw new AssertionError("cannot store more than MAX_VALUE elements"); 386 } 387 // careful of overflow! 388 int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; 389 if (newCapacity < minCapacity) { 390 newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; 391 } 392 if (newCapacity < 0) { 393 newCapacity = Integer.MAX_VALUE; 394 // guaranteed to be >= newCapacity 395 } 396 return newCapacity; 397 } 398 399 Builder() {} 400 401 /** 402 * Adds {@code element} to the {@code ImmutableCollection} being built. 403 * 404 * <p>Note that each builder class covariantly returns its own type from this method. 405 * 406 * @param element the element to add 407 * @return this {@code Builder} instance 408 * @throws NullPointerException if {@code element} is null 409 */ 410 @CanIgnoreReturnValue 411 public abstract Builder<E> add(E element); 412 413 /** 414 * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. 415 * 416 * <p>Note that each builder class overrides this method in order to covariantly return its own 417 * type. 418 * 419 * @param elements the elements to add 420 * @return this {@code Builder} instance 421 * @throws NullPointerException if {@code elements} is null or contains a null element 422 */ 423 @CanIgnoreReturnValue 424 public Builder<E> add(E... elements) { 425 for (E element : elements) { 426 add(element); 427 } 428 return this; 429 } 430 431 /** 432 * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. 433 * 434 * <p>Note that each builder class overrides this method in order to covariantly return its own 435 * type. 436 * 437 * @param elements the elements to add 438 * @return this {@code Builder} instance 439 * @throws NullPointerException if {@code elements} is null or contains a null element 440 */ 441 @CanIgnoreReturnValue 442 public Builder<E> addAll(Iterable<? extends E> elements) { 443 for (E element : elements) { 444 add(element); 445 } 446 return this; 447 } 448 449 /** 450 * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. 451 * 452 * <p>Note that each builder class overrides this method in order to covariantly return its own 453 * type. 454 * 455 * @param elements the elements to add 456 * @return this {@code Builder} instance 457 * @throws NullPointerException if {@code elements} is null or contains a null element 458 */ 459 @CanIgnoreReturnValue 460 public Builder<E> addAll(Iterator<? extends E> elements) { 461 while (elements.hasNext()) { 462 add(elements.next()); 463 } 464 return this; 465 } 466 467 /** 468 * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the 469 * elements provided to this builder. 470 * 471 * <p>Note that each builder class covariantly returns the appropriate type of {@code 472 * ImmutableCollection} from this method. 473 */ 474 public abstract ImmutableCollection<E> build(); 475 } 476 477 abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> { 478 // The first `size` elements are non-null. 479 @Nullable Object[] contents; 480 int size; 481 boolean forceCopy; 482 483 ArrayBasedBuilder(int initialCapacity) { 484 checkNonnegative(initialCapacity, "initialCapacity"); 485 this.contents = new @Nullable Object[initialCapacity]; 486 this.size = 0; 487 } 488 489 /* 490 * Expand the absolute capacity of the builder so it can accept at least the specified number of 491 * elements without being resized. Also, if we've already built a collection backed by the 492 * current array, create a new array. 493 */ 494 private void getReadyToExpandTo(int minCapacity) { 495 if (contents.length < minCapacity) { 496 this.contents = 497 Arrays.copyOf(this.contents, expandedCapacity(contents.length, minCapacity)); 498 forceCopy = false; 499 } else if (forceCopy) { 500 this.contents = contents.clone(); 501 forceCopy = false; 502 } 503 } 504 505 @CanIgnoreReturnValue 506 @Override 507 public ArrayBasedBuilder<E> add(E element) { 508 checkNotNull(element); 509 getReadyToExpandTo(size + 1); 510 contents[size++] = element; 511 return this; 512 } 513 514 @CanIgnoreReturnValue 515 @Override 516 public Builder<E> add(E... elements) { 517 addAll(elements, elements.length); 518 return this; 519 } 520 521 final void addAll(@Nullable Object[] elements, int n) { 522 checkElementsNotNull(elements, n); 523 getReadyToExpandTo(size + n); 524 /* 525 * The following call is not statically checked, since arraycopy accepts plain Object for its 526 * parameters. If it were statically checked, the checker would still be OK with it, since 527 * we're copying into a `contents` array whose type allows it to contain nulls. Still, it's 528 * worth noting that we promise not to put nulls into the array in the first `size` elements. 529 * We uphold that promise here because our callers promise that `elements` will not contain 530 * nulls in its first `n` elements. 531 */ 532 System.arraycopy(elements, 0, contents, size, n); 533 size += n; 534 } 535 536 @CanIgnoreReturnValue 537 @Override 538 public Builder<E> addAll(Iterable<? extends E> elements) { 539 if (elements instanceof Collection) { 540 Collection<?> collection = (Collection<?>) elements; 541 getReadyToExpandTo(size + collection.size()); 542 if (collection instanceof ImmutableCollection) { 543 ImmutableCollection<?> immutableCollection = (ImmutableCollection<?>) collection; 544 size = immutableCollection.copyIntoArray(contents, size); 545 return this; 546 } 547 } 548 super.addAll(elements); 549 return this; 550 } 551 } 552}