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