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