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;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import com.google.errorprone.annotations.DoNotCall;
024import com.google.errorprone.annotations.DoNotMock;
025import java.io.Serializable;
026import java.util.AbstractCollection;
027import java.util.Collection;
028import java.util.Collections;
029import java.util.HashSet;
030import java.util.Iterator;
031import java.util.List;
032import java.util.Spliterator;
033import java.util.Spliterators;
034import java.util.function.Predicate;
035import javax.annotation.CheckForNull;
036import org.checkerframework.checker.nullness.qual.Nullable;
037
038/**
039 * A {@link Collection} whose contents will never change, and which offers a few additional
040 * guarantees detailed below.
041 *
042 * <p><b>Warning:</b> avoid <i>direct</i> usage of {@link ImmutableCollection} as a type (just as
043 * with {@link Collection} itself). Prefer subtypes such as {@link ImmutableSet} or {@link
044 * ImmutableList}, which have well-defined {@link #equals} semantics, thus avoiding a common source
045 * of bugs and confusion.
046 *
047 * <h3>About <i>all</i> {@code Immutable-} collections</h3>
048 *
049 * <p>The remainder of this documentation applies to every public {@code Immutable-} type in this
050 * package, whether it is a subtype of {@code ImmutableCollection} or not.
051 *
052 * <h4>Guarantees</h4>
053 *
054 * <p>Each makes the following guarantees:
055 *
056 * <ul>
057 *   <li><b>Shallow immutability.</b> Elements can never be added, removed or replaced in this
058 *       collection. This is a stronger guarantee than that of {@link
059 *       Collections#unmodifiableCollection}, whose contents change whenever the wrapped collection
060 *       is modified.
061 *   <li><b>Null-hostility.</b> This collection will never contain a null element.
062 *   <li><b>Deterministic iteration.</b> The iteration order is always well-defined, depending on
063 *       how the collection was created. Typically this is insertion order unless an explicit
064 *       ordering is otherwise specified (e.g. {@link ImmutableSortedSet#naturalOrder}). See the
065 *       appropriate factory method for details. View collections such as {@link
066 *       ImmutableMultiset#elementSet} iterate in the same order as the parent, except as noted.
067 *   <li><b>Thread safety.</b> It is safe to access this collection concurrently from multiple
068 *       threads.
069 *   <li><b>Integrity.</b> This type cannot be subclassed outside this package (which would allow
070 *       these guarantees to be violated).
071 * </ul>
072 *
073 * <h4>"Interfaces", not implementations</h4>
074 *
075 * <p>These are classes instead of interfaces to prevent external subtyping, but should be thought
076 * of as interfaces in every important sense. Each public class such as {@link ImmutableSet} is a
077 * <i>type</i> offering meaningful behavioral guarantees. This is substantially different from the
078 * case of (say) {@link HashSet}, which is an <i>implementation</i>, with semantics that were
079 * largely defined by its supertype.
080 *
081 * <p>For field types and method return types, you should generally use the immutable type (such as
082 * {@link ImmutableList}) instead of the general collection interface type (such as {@link List}).
083 * This communicates to your callers all of the semantic guarantees listed above, which is almost
084 * always very useful information.
085 *
086 * <p>On the other hand, a <i>parameter</i> type of {@link ImmutableList} is generally a nuisance to
087 * callers. Instead, accept {@link Iterable} and have your method or constructor body pass it to the
088 * appropriate {@code copyOf} method itself.
089 *
090 * <p>Expressing the immutability guarantee directly in the type that user code references is a
091 * powerful advantage. Although Java offers certain immutable collection factory methods, such as
092 * {@link Collections#singleton(Object)} and <a
093 * href="https://docs.oracle.com/javase/9/docs/api/java/util/Set.html#immutable">{@code Set.of}</a>,
094 * we recommend using <i>these</i> classes instead for this reason (as well as for consistency).
095 *
096 * <h4>Creation</h4>
097 *
098 * <p>Except for logically "abstract" types like {@code ImmutableCollection} itself, each {@code
099 * Immutable} type provides the static operations you need to obtain instances of that type. These
100 * usually include:
101 *
102 * <ul>
103 *   <li>Static methods named {@code of}, accepting an explicit list of elements or entries.
104 *   <li>Static methods named {@code copyOf} (or {@code copyOfSorted}), accepting an existing
105 *       collection whose contents should be copied.
106 *   <li>A static nested {@code Builder} class which can be used to populate a new immutable
107 *       instance.
108 * </ul>
109 *
110 * <h4>Warnings</h4>
111 *
112 * <ul>
113 *   <li><b>Warning:</b> as with any collection, it is almost always a bad idea to modify an element
114 *       (in a way that affects its {@link Object#equals} behavior) while it is contained in a
115 *       collection. Undefined behavior and bugs will result. It's generally best to avoid using
116 *       mutable objects as elements at all, as many users may expect your "immutable" object to be
117 *       <i>deeply</i> immutable.
118 * </ul>
119 *
120 * <h4>Performance notes</h4>
121 *
122 * <ul>
123 *   <li>Implementations can be generally assumed to prioritize memory efficiency, then speed of
124 *       access, and lastly speed of creation.
125 *   <li>The {@code copyOf} methods will sometimes recognize that the actual copy operation is
126 *       unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only
127 *       once. This reduces the expense of habitually making defensive copies at API boundaries.
128 *       However, the precise conditions for skipping the copy operation are undefined.
129 *   <li><b>Warning:</b> a view collection such as {@link ImmutableMap#keySet} or {@link
130 *       ImmutableList#subList} may retain a reference to the entire data set, preventing it from
131 *       being garbage collected. If some of the data is no longer reachable through other means,
132 *       this constitutes a memory leak. Pass the view collection to the appropriate {@code copyOf}
133 *       method to obtain a correctly-sized copy.
134 *   <li>The performance of using the associated {@code Builder} class can be assumed to be no
135 *       worse, and possibly better, than creating a mutable collection and copying it.
136 *   <li>Implementations generally do not cache hash codes. If your element or key type has a slow
137 *       {@code hashCode} implementation, it should cache it itself.
138 * </ul>
139 *
140 * <h4>Example usage</h4>
141 *
142 * <pre>{@code
143 * class Foo {
144 *   private static final ImmutableSet<String> RESERVED_CODES =
145 *       ImmutableSet.of("AZ", "CQ", "ZX");
146 *
147 *   private final ImmutableSet<String> codes;
148 *
149 *   public Foo(Iterable<String> codes) {
150 *     this.codes = ImmutableSet.copyOf(codes);
151 *     checkArgument(Collections.disjoint(this.codes, RESERVED_CODES));
152 *   }
153 * }
154 * }</pre>
155 *
156 * <h3>See also</h3>
157 *
158 * <p>See the Guava User Guide article on <a href=
159 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
160 *
161 * @since 2.0
162 */
163@DoNotMock("Use ImmutableList.of or another implementation")
164@GwtCompatible(emulated = true)
165@SuppressWarnings("serial") // we're overriding default serialization
166@ElementTypesAreNonnullByDefault
167// TODO(kevinb): I think we should push everything down to "BaseImmutableCollection" or something,
168// just to do everything we can to emphasize the "practically an interface" nature of this class.
169public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable {
170  /*
171   * We expect SIZED (and SUBSIZED, if applicable) to be added by the spliterator factory methods.
172   * These are properties of the collection as a whole; SIZED and SUBSIZED are more properties of
173   * the spliterator implementation.
174   */
175  static final int SPLITERATOR_CHARACTERISTICS =
176      Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED;
177
178  ImmutableCollection() {}
179
180  /** Returns an unmodifiable iterator across the elements in this collection. */
181  @Override
182  public abstract UnmodifiableIterator<E> iterator();
183
184  @Override
185  public Spliterator<E> spliterator() {
186    return Spliterators.spliterator(this, SPLITERATOR_CHARACTERISTICS);
187  }
188
189  private static final Object[] EMPTY_ARRAY = {};
190
191  @Override
192  public final Object[] toArray() {
193    return toArray(EMPTY_ARRAY);
194  }
195
196  @CanIgnoreReturnValue
197  @Override
198  /*
199   * This suppression is here for two reasons:
200   *
201   * 1. b/192354773 in our checker affects toArray declarations.
202   *
203   * 2. `other[size] = null` is unsound. We could "fix" this by requiring callers to pass in an
204   * array with a nullable element type. But probably they usually want an array with a non-nullable
205   * type. That said, we could *accept* a `@Nullable T[]` (which, given that we treat arrays as
206   * covariant, would still permit a plain `T[]`) and return a plain `T[]`. But of course that would
207   * require its own suppression, since it is also unsound. toArray(T[]) is just a mess from a
208   * nullness perspective. The signature below at least has the virtue of being relatively simple.
209   */
210  @SuppressWarnings("nullness")
211  public final <T extends @Nullable Object> T[] toArray(T[] other) {
212    checkNotNull(other);
213    int size = size();
214
215    if (other.length < size) {
216      Object[] internal = internalArray();
217      if (internal != null) {
218        return Platform.copy(internal, internalArrayStart(), internalArrayEnd(), other);
219      }
220      other = ObjectArrays.newArray(other, size);
221    } else if (other.length > size) {
222      other[size] = null;
223    }
224    copyIntoArray(other, 0);
225    return other;
226  }
227
228  /** If this collection is backed by an array of its elements in insertion order, returns it. */
229  @CheckForNull
230  Object[] internalArray() {
231    return null;
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 start.
237   */
238  int internalArrayStart() {
239    throw new UnsupportedOperationException();
240  }
241
242  /**
243   * If this collection is backed by an array of its elements in insertion order, returns the offset
244   * where this collection's elements end.
245   */
246  int internalArrayEnd() {
247    throw new UnsupportedOperationException();
248  }
249
250  @Override
251  public abstract boolean contains(@CheckForNull Object object);
252
253  /**
254   * Guaranteed to throw an exception and leave the collection unmodified.
255   *
256   * @throws UnsupportedOperationException always
257   * @deprecated Unsupported operation.
258   */
259  @CanIgnoreReturnValue
260  @Deprecated
261  @Override
262  @DoNotCall("Always throws UnsupportedOperationException")
263  public final boolean add(E e) {
264    throw new UnsupportedOperationException();
265  }
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 remove(@CheckForNull Object object) {
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 addAll(Collection<? extends E> newElements) {
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 removeAll(Collection<?> oldElements) {
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 removeIf(Predicate<? super E> filter) {
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  @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    switch (size()) {
361      case 0:
362        return ImmutableList.of();
363      case 1:
364        return ImmutableList.of(iterator().next());
365      default:
366        return new RegularImmutableAsList<E>(this, toArray());
367    }
368  }
369
370  /**
371   * Returns {@code true} if this immutable collection's implementation contains references to
372   * user-created objects that aren't accessible via this collection's methods. This is generally
373   * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
374   * memory leaks.
375   */
376  abstract boolean isPartialView();
377
378  /**
379   * Copies the contents of this immutable collection into the specified array at the specified
380   * offset. Returns {@code offset + size()}.
381   */
382  @CanIgnoreReturnValue
383  int copyIntoArray(@Nullable Object[] dst, int offset) {
384    for (E e : this) {
385      dst[offset++] = e;
386    }
387    return offset;
388  }
389
390  Object writeReplace() {
391    // We serialize by default to ImmutableList, the simplest thing that works.
392    return new ImmutableList.SerializedForm(toArray());
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 AssertionError("cannot store more than MAX_VALUE elements");
407      }
408      // careful of overflow!
409      int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
410      if (newCapacity < minCapacity) {
411        newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
412      }
413      if (newCapacity < 0) {
414        newCapacity = Integer.MAX_VALUE;
415        // guaranteed to be >= newCapacity
416      }
417      return newCapacity;
418    }
419
420    Builder() {}
421
422    /**
423     * Adds {@code element} to the {@code ImmutableCollection} being built.
424     *
425     * <p>Note that each builder class covariantly returns its own type from this method.
426     *
427     * @param element the element to add
428     * @return this {@code Builder} instance
429     * @throws NullPointerException if {@code element} is null
430     */
431    @CanIgnoreReturnValue
432    public abstract Builder<E> add(E element);
433
434    /**
435     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
436     *
437     * <p>Note that each builder class overrides this method in order to covariantly return its own
438     * type.
439     *
440     * @param elements the elements to add
441     * @return this {@code Builder} instance
442     * @throws NullPointerException if {@code elements} is null or contains a null element
443     */
444    @CanIgnoreReturnValue
445    public Builder<E> add(E... elements) {
446      for (E element : elements) {
447        add(element);
448      }
449      return this;
450    }
451
452    /**
453     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
454     *
455     * <p>Note that each builder class overrides this method in order to covariantly return its own
456     * type.
457     *
458     * @param elements the elements to add
459     * @return this {@code Builder} instance
460     * @throws NullPointerException if {@code elements} is null or contains a null element
461     */
462    @CanIgnoreReturnValue
463    public Builder<E> addAll(Iterable<? extends E> elements) {
464      for (E element : elements) {
465        add(element);
466      }
467      return this;
468    }
469
470    /**
471     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
472     *
473     * <p>Note that each builder class overrides this method in order to covariantly return its own
474     * type.
475     *
476     * @param elements the elements to add
477     * @return this {@code Builder} instance
478     * @throws NullPointerException if {@code elements} is null or contains a null element
479     */
480    @CanIgnoreReturnValue
481    public Builder<E> addAll(Iterator<? extends E> elements) {
482      while (elements.hasNext()) {
483        add(elements.next());
484      }
485      return this;
486    }
487
488    /**
489     * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the
490     * elements provided to this builder.
491     *
492     * <p>Note that each builder class covariantly returns the appropriate type of {@code
493     * ImmutableCollection} from this method.
494     */
495    public abstract ImmutableCollection<E> build();
496  }
497}