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.<E>of() : ImmutableList.<E>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 AssertionError("cannot store more than MAX_VALUE elements");
408      }
409      // careful of overflow!
410      int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
411      if (newCapacity < minCapacity) {
412        newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
413      }
414      if (newCapacity < 0) {
415        newCapacity = Integer.MAX_VALUE;
416        // guaranteed to be >= newCapacity
417      }
418      return newCapacity;
419    }
420
421    Builder() {}
422
423    /**
424     * Adds {@code element} to the {@code ImmutableCollection} being built.
425     *
426     * <p>Note that each builder class covariantly returns its own type from this method.
427     *
428     * @param element the element to add
429     * @return this {@code Builder} instance
430     * @throws NullPointerException if {@code element} is null
431     */
432    @CanIgnoreReturnValue
433    public abstract Builder<E> add(E element);
434
435    /**
436     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
437     *
438     * <p>Note that each builder class overrides this method in order to covariantly return its own
439     * type.
440     *
441     * @param elements the elements to add
442     * @return this {@code Builder} instance
443     * @throws NullPointerException if {@code elements} is null or contains a null element
444     */
445    @CanIgnoreReturnValue
446    public Builder<E> add(E... elements) {
447      for (E element : elements) {
448        add(element);
449      }
450      return this;
451    }
452
453    /**
454     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
455     *
456     * <p>Note that each builder class overrides this method in order to covariantly return its own
457     * type.
458     *
459     * @param elements the elements to add
460     * @return this {@code Builder} instance
461     * @throws NullPointerException if {@code elements} is null or contains a null element
462     */
463    @CanIgnoreReturnValue
464    public Builder<E> addAll(Iterable<? extends E> elements) {
465      for (E element : elements) {
466        add(element);
467      }
468      return this;
469    }
470
471    /**
472     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
473     *
474     * <p>Note that each builder class overrides this method in order to covariantly return its own
475     * type.
476     *
477     * @param elements the elements to add
478     * @return this {@code Builder} instance
479     * @throws NullPointerException if {@code elements} is null or contains a null element
480     */
481    @CanIgnoreReturnValue
482    public Builder<E> addAll(Iterator<? extends E> elements) {
483      while (elements.hasNext()) {
484        add(elements.next());
485      }
486      return this;
487    }
488
489    /**
490     * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the
491     * elements provided to this builder.
492     *
493     * <p>Note that each builder class covariantly returns the appropriate type of {@code
494     * ImmutableCollection} from this method.
495     */
496    public abstract ImmutableCollection<E> build();
497  }
498
499  abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> {
500    // The first `size` elements are non-null.
501    @Nullable Object[] contents;
502    int size;
503    boolean forceCopy;
504
505    ArrayBasedBuilder(int initialCapacity) {
506      checkNonnegative(initialCapacity, "initialCapacity");
507      this.contents = new @Nullable Object[initialCapacity];
508      this.size = 0;
509    }
510
511    /*
512     * Expand the absolute capacity of the builder so it can accept at least the specified number of
513     * elements without being resized. Also, if we've already built a collection backed by the
514     * current array, create a new array.
515     */
516    private void getReadyToExpandTo(int minCapacity) {
517      if (contents.length < minCapacity) {
518        this.contents =
519            Arrays.copyOf(this.contents, expandedCapacity(contents.length, minCapacity));
520        forceCopy = false;
521      } else if (forceCopy) {
522        this.contents = contents.clone();
523        forceCopy = false;
524      }
525    }
526
527    @CanIgnoreReturnValue
528    @Override
529    public ArrayBasedBuilder<E> add(E element) {
530      checkNotNull(element);
531      getReadyToExpandTo(size + 1);
532      contents[size++] = element;
533      return this;
534    }
535
536    @CanIgnoreReturnValue
537    @Override
538    public Builder<E> add(E... elements) {
539      addAll(elements, elements.length);
540      return this;
541    }
542
543    final void addAll(@Nullable Object[] elements, int n) {
544      checkElementsNotNull(elements, n);
545      getReadyToExpandTo(size + n);
546      /*
547       * The following call is not statically checked, since arraycopy accepts plain Object for its
548       * parameters. If it were statically checked, the checker would still be OK with it, since
549       * we're copying into a `contents` array whose type allows it to contain nulls. Still, it's
550       * worth noting that we promise not to put nulls into the array in the first `size` elements.
551       * We uphold that promise here because our callers promise that `elements` will not contain
552       * nulls in its first `n` elements.
553       */
554      System.arraycopy(elements, 0, contents, size, n);
555      size += n;
556    }
557
558    @CanIgnoreReturnValue
559    @Override
560    public Builder<E> addAll(Iterable<? extends E> elements) {
561      if (elements instanceof Collection) {
562        Collection<?> collection = (Collection<?>) elements;
563        getReadyToExpandTo(size + collection.size());
564        if (collection instanceof ImmutableCollection) {
565          ImmutableCollection<?> immutableCollection = (ImmutableCollection<?>) collection;
566          size = immutableCollection.copyIntoArray(contents, size);
567          return this;
568        }
569      }
570      super.addAll(elements);
571      return this;
572    }
573  }
574
575  private static final long serialVersionUID = 0xdecaf;
576}