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