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