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