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