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