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// TODO(kevinb): I think we should push everything down to "BaseImmutableCollection" or something,
173// just to do everything we can to emphasize the "practically an interface" nature of this class.
174public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable {
175  /*
176   * We expect SIZED (and SUBSIZED, if applicable) to be added by the spliterator factory methods.
177   * These are properties of the collection as a whole; SIZED and SUBSIZED are more properties of
178   * the spliterator implementation.
179   */
180  @SuppressWarnings("Java7ApiChecker")
181  // @IgnoreJRERequirement is not necessary because this compiles down to a constant.
182  // (which is fortunate because Animal Sniffer doesn't look for @IgnoreJRERequirement on fields)
183  static final int SPLITERATOR_CHARACTERISTICS =
184      Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED;
185
186  ImmutableCollection() {}
187
188  /** Returns an unmodifiable iterator across the elements in this collection. */
189  @Override
190  public abstract UnmodifiableIterator<E> iterator();
191
192  @Override
193  @SuppressWarnings("Java7ApiChecker")
194  @IgnoreJRERequirement // used only from APIs with Java 8 types in them
195  // (not used within guava-android as of this writing, but we include it in the jar as a test)
196  public Spliterator<E> spliterator() {
197    return Spliterators.spliterator(this, SPLITERATOR_CHARACTERISTICS);
198  }
199
200  private static final Object[] EMPTY_ARRAY = {};
201
202  @Override
203  @J2ktIncompatible // Incompatible return type change. Use inherited (unoptimized) implementation
204  public final Object[] toArray() {
205    return toArray(EMPTY_ARRAY);
206  }
207
208  @CanIgnoreReturnValue
209  @Override
210  /*
211   * This suppression is here for two reasons:
212   *
213   * 1. b/192354773 in our checker affects toArray declarations.
214   *
215   * 2. `other[size] = null` is unsound. We could "fix" this by requiring callers to pass in an
216   * array with a nullable element type. But probably they usually want an array with a non-nullable
217   * type. That said, we could *accept* a `@Nullable T[]` (which, given that we treat arrays as
218   * covariant, would still permit a plain `T[]`) and return a plain `T[]`. But of course that would
219   * require its own suppression, since it is also unsound. toArray(T[]) is just a mess from a
220   * nullness perspective. The signature below at least has the virtue of being relatively simple.
221   */
222  @SuppressWarnings("nullness")
223  public final <T extends @Nullable Object> T[] toArray(T[] other) {
224    checkNotNull(other);
225    int size = size();
226
227    if (other.length < size) {
228      Object[] internal = internalArray();
229      if (internal != null) {
230        return Platform.copy(internal, internalArrayStart(), internalArrayEnd(), other);
231      }
232      other = ObjectArrays.newArray(other, size);
233    } else if (other.length > size) {
234      other[size] = null;
235    }
236    copyIntoArray(other, 0);
237    return other;
238  }
239
240  /** If this collection is backed by an array of its elements in insertion order, returns it. */
241  @CheckForNull
242  @Nullable
243  Object[] internalArray() {
244    return null;
245  }
246
247  /**
248   * If this collection is backed by an array of its elements in insertion order, returns the offset
249   * where this collection's elements start.
250   */
251  int internalArrayStart() {
252    throw new UnsupportedOperationException();
253  }
254
255  /**
256   * If this collection is backed by an array of its elements in insertion order, returns the offset
257   * where this collection's elements end.
258   */
259  int internalArrayEnd() {
260    throw new UnsupportedOperationException();
261  }
262
263  @Override
264  public abstract boolean contains(@CheckForNull Object object);
265
266  /**
267   * Guaranteed to throw an exception and leave the collection unmodified.
268   *
269   * @throws UnsupportedOperationException always
270   * @deprecated Unsupported operation.
271   */
272  @CanIgnoreReturnValue
273  @Deprecated
274  @Override
275  @DoNotCall("Always throws UnsupportedOperationException")
276  public final boolean add(E e) {
277    throw new UnsupportedOperationException();
278  }
279
280  /**
281   * Guaranteed to throw an exception and leave the collection unmodified.
282   *
283   * @throws UnsupportedOperationException always
284   * @deprecated Unsupported operation.
285   */
286  @CanIgnoreReturnValue
287  @Deprecated
288  @Override
289  @DoNotCall("Always throws UnsupportedOperationException")
290  public final boolean remove(@CheckForNull Object object) {
291    throw new UnsupportedOperationException();
292  }
293
294  /**
295   * Guaranteed to throw an exception and leave the collection unmodified.
296   *
297   * @throws UnsupportedOperationException always
298   * @deprecated Unsupported operation.
299   */
300  @CanIgnoreReturnValue
301  @Deprecated
302  @Override
303  @DoNotCall("Always throws UnsupportedOperationException")
304  public final boolean addAll(Collection<? extends E> newElements) {
305    throw new UnsupportedOperationException();
306  }
307
308  /**
309   * Guaranteed to throw an exception and leave the collection unmodified.
310   *
311   * @throws UnsupportedOperationException always
312   * @deprecated Unsupported operation.
313   */
314  @CanIgnoreReturnValue
315  @Deprecated
316  @Override
317  @DoNotCall("Always throws UnsupportedOperationException")
318  public final boolean removeAll(Collection<?> oldElements) {
319    throw new UnsupportedOperationException();
320  }
321
322  /**
323   * Guaranteed to throw an exception and leave the collection unmodified.
324   *
325   * @throws UnsupportedOperationException always
326   * @deprecated Unsupported operation.
327   */
328  @CanIgnoreReturnValue
329  @Deprecated
330  @Override
331  @DoNotCall("Always throws UnsupportedOperationException")
332  public final boolean retainAll(Collection<?> elementsToKeep) {
333    throw new UnsupportedOperationException();
334  }
335
336  /**
337   * Guaranteed to throw an exception and leave the collection unmodified.
338   *
339   * @throws UnsupportedOperationException always
340   * @deprecated Unsupported operation.
341   */
342  @Deprecated
343  @Override
344  @DoNotCall("Always throws UnsupportedOperationException")
345  public final void clear() {
346    throw new UnsupportedOperationException();
347  }
348
349  /**
350   * Returns an {@code ImmutableList} containing the same elements, in the same order, as this
351   * collection.
352   *
353   * <p><b>Performance note:</b> in most cases this method can return quickly without actually
354   * copying anything. The exact circumstances under which the copy is performed are undefined and
355   * subject to change.
356   *
357   * @since 2.0
358   */
359  public ImmutableList<E> asList() {
360    return isEmpty() ? ImmutableList.of() : ImmutableList.asImmutableList(toArray());
361  }
362
363  /**
364   * Returns {@code true} if this immutable collection's implementation contains references to
365   * user-created objects that aren't accessible via this collection's methods. This is generally
366   * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
367   * memory leaks.
368   */
369  abstract boolean isPartialView();
370
371  /**
372   * Copies the contents of this immutable collection into the specified array at the specified
373   * offset. Returns {@code offset + size()}.
374   */
375  @CanIgnoreReturnValue
376  int copyIntoArray(@Nullable Object[] dst, int offset) {
377    for (E e : this) {
378      dst[offset++] = e;
379    }
380    return offset;
381  }
382
383  @J2ktIncompatible // serialization
384  @GwtIncompatible // serialization
385  Object writeReplace() {
386    // We serialize by default to ImmutableList, the simplest thing that works.
387    return new ImmutableList.SerializedForm(toArray());
388  }
389
390  @J2ktIncompatible // serialization
391  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
392    throw new InvalidObjectException("Use SerializedForm");
393  }
394
395  /**
396   * Abstract base class for builders of {@link ImmutableCollection} types.
397   *
398   * @since 10.0
399   */
400  @DoNotMock
401  public abstract static class Builder<E> {
402    static final int DEFAULT_INITIAL_CAPACITY = 4;
403
404    static int expandedCapacity(int oldCapacity, int minCapacity) {
405      if (minCapacity < 0) {
406        throw new IllegalArgumentException("cannot store more than Integer.MAX_VALUE elements");
407      } else if (minCapacity <= oldCapacity) {
408        return oldCapacity;
409      }
410      // careful of overflow!
411      int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
412      if (newCapacity < minCapacity) {
413        newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
414      }
415      if (newCapacity < 0) {
416        newCapacity = Integer.MAX_VALUE;
417        // guaranteed to be >= newCapacity
418      }
419      return newCapacity;
420    }
421
422    Builder() {}
423
424    /**
425     * Adds {@code element} to the {@code ImmutableCollection} being built.
426     *
427     * <p>Note that each builder class covariantly returns its own type from this method.
428     *
429     * @param element the element to add
430     * @return this {@code Builder} instance
431     * @throws NullPointerException if {@code element} is null
432     */
433    @CanIgnoreReturnValue
434    public abstract Builder<E> add(E element);
435
436    /**
437     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
438     *
439     * <p>Note that each builder class overrides this method in order to covariantly return its own
440     * type.
441     *
442     * @param elements the elements to add
443     * @return this {@code Builder} instance
444     * @throws NullPointerException if {@code elements} is null or contains a null element
445     */
446    @CanIgnoreReturnValue
447    public Builder<E> add(E... elements) {
448      for (E element : elements) {
449        add(element);
450      }
451      return this;
452    }
453
454    /**
455     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
456     *
457     * <p>Note that each builder class overrides this method in order to covariantly return its own
458     * type.
459     *
460     * @param elements the elements to add
461     * @return this {@code Builder} instance
462     * @throws NullPointerException if {@code elements} is null or contains a null element
463     */
464    @CanIgnoreReturnValue
465    public Builder<E> addAll(Iterable<? extends E> elements) {
466      for (E element : elements) {
467        add(element);
468      }
469      return this;
470    }
471
472    /**
473     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
474     *
475     * <p>Note that each builder class overrides this method in order to covariantly return its own
476     * type.
477     *
478     * @param elements the elements to add
479     * @return this {@code Builder} instance
480     * @throws NullPointerException if {@code elements} is null or contains a null element
481     */
482    @CanIgnoreReturnValue
483    public Builder<E> addAll(Iterator<? extends E> elements) {
484      while (elements.hasNext()) {
485        add(elements.next());
486      }
487      return this;
488    }
489
490    /**
491     * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the
492     * elements provided to this builder.
493     *
494     * <p>Note that each builder class covariantly returns the appropriate type of {@code
495     * ImmutableCollection} from this method.
496     */
497    public abstract ImmutableCollection<E> build();
498  }
499
500  abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> {
501    // The first `size` elements are non-null.
502    @Nullable Object[] contents;
503    int size;
504    boolean forceCopy;
505
506    ArrayBasedBuilder(int initialCapacity) {
507      checkNonnegative(initialCapacity, "initialCapacity");
508      this.contents = new @Nullable Object[initialCapacity];
509      this.size = 0;
510    }
511
512    /*
513     * Expand the absolute capacity of the builder so it can accept at least the specified number of
514     * elements without being resized. Also, if we've already built a collection backed by the
515     * current array, create a new array.
516     */
517    private void ensureRoomFor(int newElements) {
518      @Nullable Object[] contents = this.contents;
519      int newCapacity = expandedCapacity(contents.length, size + newElements);
520      // expandedCapacity handles the overflow case
521      if (newCapacity > contents.length || forceCopy) {
522        this.contents = Arrays.copyOf(this.contents, newCapacity);
523        forceCopy = false;
524      }
525    }
526
527    @CanIgnoreReturnValue
528    @Override
529    public ArrayBasedBuilder<E> add(E element) {
530      checkNotNull(element);
531      ensureRoomFor(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      ensureRoomFor(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        ensureRoomFor(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}