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