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