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