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