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; 020 021import com.google.common.annotations.GwtCompatible; 022import com.google.common.annotations.J2ktIncompatible; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import com.google.errorprone.annotations.DoNotCall; 025import com.google.errorprone.annotations.DoNotMock; 026import java.io.InvalidObjectException; 027import java.io.ObjectInputStream; 028import java.io.Serializable; 029import java.util.AbstractCollection; 030import java.util.Collection; 031import java.util.Collections; 032import java.util.HashSet; 033import java.util.Iterator; 034import java.util.List; 035import java.util.Spliterator; 036import java.util.Spliterators; 037import java.util.function.Predicate; 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 * We expect SIZED (and SUBSIZED, if applicable) to be added by the spliterator factory methods. 175 * These are properties of the collection as a whole; SIZED and SUBSIZED are more properties of 176 * the spliterator implementation. 177 */ 178 static final int SPLITERATOR_CHARACTERISTICS = 179 Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED; 180 181 ImmutableCollection() {} 182 183 /** Returns an unmodifiable iterator across the elements in this collection. */ 184 @Override 185 public abstract UnmodifiableIterator<E> iterator(); 186 187 @Override 188 public Spliterator<E> spliterator() { 189 return Spliterators.spliterator(this, SPLITERATOR_CHARACTERISTICS); 190 } 191 192 private static final Object[] EMPTY_ARRAY = {}; 193 194 @Override 195 @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation 196 public final Object[] toArray() { 197 return toArray(EMPTY_ARRAY); 198 } 199 200 @CanIgnoreReturnValue 201 @Override 202 /* 203 * This suppression is here for two reasons: 204 * 205 * 1. b/192354773 in our checker affects toArray declarations. 206 * 207 * 2. `other[size] = null` is unsound. We could "fix" this by requiring callers to pass in an 208 * array with a nullable element type. But probably they usually want an array with a non-nullable 209 * type. That said, we could *accept* a `@Nullable T[]` (which, given that we treat arrays as 210 * covariant, would still permit a plain `T[]`) and return a plain `T[]`. But of course that would 211 * require its own suppression, since it is also unsound. toArray(T[]) is just a mess from a 212 * nullness perspective. The signature below at least has the virtue of being relatively simple. 213 */ 214 @SuppressWarnings("nullness") 215 public final <T extends @Nullable Object> T[] toArray(T[] other) { 216 checkNotNull(other); 217 int size = size(); 218 219 if (other.length < size) { 220 Object[] internal = internalArray(); 221 if (internal != null) { 222 return Platform.copy(internal, internalArrayStart(), internalArrayEnd(), other); 223 } 224 other = ObjectArrays.newArray(other, size); 225 } else if (other.length > size) { 226 other[size] = null; 227 } 228 copyIntoArray(other, 0); 229 return other; 230 } 231 232 /** If this collection is backed by an array of its elements in insertion order, returns it. */ 233 @CheckForNull 234 Object[] internalArray() { 235 return null; 236 } 237 238 /** 239 * If this collection is backed by an array of its elements in insertion order, returns the offset 240 * where this collection's elements start. 241 */ 242 int internalArrayStart() { 243 throw new UnsupportedOperationException(); 244 } 245 246 /** 247 * If this collection is backed by an array of its elements in insertion order, returns the offset 248 * where this collection's elements end. 249 */ 250 int internalArrayEnd() { 251 throw new UnsupportedOperationException(); 252 } 253 254 @Override 255 public abstract boolean contains(@CheckForNull Object object); 256 257 /** 258 * Guaranteed to throw an exception and leave the collection unmodified. 259 * 260 * @throws UnsupportedOperationException always 261 * @deprecated Unsupported operation. 262 */ 263 @CanIgnoreReturnValue 264 @Deprecated 265 @Override 266 @DoNotCall("Always throws UnsupportedOperationException") 267 public final boolean add(E e) { 268 throw new UnsupportedOperationException(); 269 } 270 271 /** 272 * Guaranteed to throw an exception and leave the collection unmodified. 273 * 274 * @throws UnsupportedOperationException always 275 * @deprecated Unsupported operation. 276 */ 277 @CanIgnoreReturnValue 278 @Deprecated 279 @Override 280 @DoNotCall("Always throws UnsupportedOperationException") 281 public final boolean remove(@CheckForNull Object object) { 282 throw new UnsupportedOperationException(); 283 } 284 285 /** 286 * Guaranteed to throw an exception and leave the collection unmodified. 287 * 288 * @throws UnsupportedOperationException always 289 * @deprecated Unsupported operation. 290 */ 291 @CanIgnoreReturnValue 292 @Deprecated 293 @Override 294 @DoNotCall("Always throws UnsupportedOperationException") 295 public final boolean addAll(Collection<? extends E> newElements) { 296 throw new UnsupportedOperationException(); 297 } 298 299 /** 300 * Guaranteed to throw an exception and leave the collection unmodified. 301 * 302 * @throws UnsupportedOperationException always 303 * @deprecated Unsupported operation. 304 */ 305 @CanIgnoreReturnValue 306 @Deprecated 307 @Override 308 @DoNotCall("Always throws UnsupportedOperationException") 309 public final boolean removeAll(Collection<?> oldElements) { 310 throw new UnsupportedOperationException(); 311 } 312 313 /** 314 * Guaranteed to throw an exception and leave the collection unmodified. 315 * 316 * @throws UnsupportedOperationException always 317 * @deprecated Unsupported operation. 318 */ 319 @CanIgnoreReturnValue 320 @Deprecated 321 @Override 322 @DoNotCall("Always throws UnsupportedOperationException") 323 public final boolean removeIf(Predicate<? super E> filter) { 324 throw new UnsupportedOperationException(); 325 } 326 327 /** 328 * Guaranteed to throw an exception and leave the collection unmodified. 329 * 330 * @throws UnsupportedOperationException always 331 * @deprecated Unsupported operation. 332 */ 333 @Deprecated 334 @Override 335 @DoNotCall("Always throws UnsupportedOperationException") 336 public final boolean retainAll(Collection<?> elementsToKeep) { 337 throw new UnsupportedOperationException(); 338 } 339 340 /** 341 * Guaranteed to throw an exception and leave the collection unmodified. 342 * 343 * @throws UnsupportedOperationException always 344 * @deprecated Unsupported operation. 345 */ 346 @Deprecated 347 @Override 348 @DoNotCall("Always throws UnsupportedOperationException") 349 public final void clear() { 350 throw new UnsupportedOperationException(); 351 } 352 353 /** 354 * Returns an {@code ImmutableList} containing the same elements, in the same order, as this 355 * collection. 356 * 357 * <p><b>Performance note:</b> in most cases this method can return quickly without actually 358 * copying anything. The exact circumstances under which the copy is performed are undefined and 359 * subject to change. 360 * 361 * @since 2.0 362 */ 363 public ImmutableList<E> asList() { 364 switch (size()) { 365 case 0: 366 return ImmutableList.of(); 367 case 1: 368 return ImmutableList.of(iterator().next()); 369 default: 370 return new RegularImmutableAsList<E>(this, toArray()); 371 } 372 } 373 374 /** 375 * Returns {@code true} if this immutable collection's implementation contains references to 376 * user-created objects that aren't accessible via this collection's methods. This is generally 377 * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid 378 * memory leaks. 379 */ 380 abstract boolean isPartialView(); 381 382 /** 383 * Copies the contents of this immutable collection into the specified array at the specified 384 * offset. Returns {@code offset + size()}. 385 */ 386 @CanIgnoreReturnValue 387 int copyIntoArray(@Nullable Object[] dst, int offset) { 388 for (E e : this) { 389 dst[offset++] = e; 390 } 391 return offset; 392 } 393 394 @J2ktIncompatible // serialization 395 Object writeReplace() { 396 // We serialize by default to ImmutableList, the simplest thing that works. 397 return new ImmutableList.SerializedForm(toArray()); 398 } 399 400 @J2ktIncompatible // serialization 401 private void readObject(ObjectInputStream stream) throws InvalidObjectException { 402 throw new InvalidObjectException("Use SerializedForm"); 403 } 404 405 /** 406 * Abstract base class for builders of {@link ImmutableCollection} types. 407 * 408 * @since 10.0 409 */ 410 @DoNotMock 411 public abstract static class Builder<E> { 412 static final int DEFAULT_INITIAL_CAPACITY = 4; 413 414 static int expandedCapacity(int oldCapacity, int minCapacity) { 415 if (minCapacity < 0) { 416 throw new AssertionError("cannot store more than MAX_VALUE elements"); 417 } 418 // careful of overflow! 419 int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; 420 if (newCapacity < minCapacity) { 421 newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; 422 } 423 if (newCapacity < 0) { 424 newCapacity = Integer.MAX_VALUE; 425 // guaranteed to be >= newCapacity 426 } 427 return newCapacity; 428 } 429 430 Builder() {} 431 432 /** 433 * Adds {@code element} to the {@code ImmutableCollection} being built. 434 * 435 * <p>Note that each builder class covariantly returns its own type from this method. 436 * 437 * @param element the element to add 438 * @return this {@code Builder} instance 439 * @throws NullPointerException if {@code element} is null 440 */ 441 @CanIgnoreReturnValue 442 public abstract Builder<E> add(E element); 443 444 /** 445 * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. 446 * 447 * <p>Note that each builder class overrides this method in order to covariantly return its own 448 * type. 449 * 450 * @param elements the elements to add 451 * @return this {@code Builder} instance 452 * @throws NullPointerException if {@code elements} is null or contains a null element 453 */ 454 @CanIgnoreReturnValue 455 public Builder<E> add(E... elements) { 456 for (E element : elements) { 457 add(element); 458 } 459 return this; 460 } 461 462 /** 463 * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. 464 * 465 * <p>Note that each builder class overrides this method in order to covariantly return its own 466 * type. 467 * 468 * @param elements the elements to add 469 * @return this {@code Builder} instance 470 * @throws NullPointerException if {@code elements} is null or contains a null element 471 */ 472 @CanIgnoreReturnValue 473 public Builder<E> addAll(Iterable<? extends E> elements) { 474 for (E element : elements) { 475 add(element); 476 } 477 return this; 478 } 479 480 /** 481 * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. 482 * 483 * <p>Note that each builder class overrides this method in order to covariantly return its own 484 * type. 485 * 486 * @param elements the elements to add 487 * @return this {@code Builder} instance 488 * @throws NullPointerException if {@code elements} is null or contains a null element 489 */ 490 @CanIgnoreReturnValue 491 public Builder<E> addAll(Iterator<? extends E> elements) { 492 while (elements.hasNext()) { 493 add(elements.next()); 494 } 495 return this; 496 } 497 498 /** 499 * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the 500 * elements provided to this builder. 501 * 502 * <p>Note that each builder class covariantly returns the appropriate type of {@code 503 * ImmutableCollection} from this method. 504 */ 505 public abstract ImmutableCollection<E> build(); 506 } 507}