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;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.errorprone.annotations.CanIgnoreReturnValue;
025import com.google.errorprone.annotations.DoNotCall;
026import com.google.errorprone.annotations.DoNotMock;
027import java.io.Serializable;
028import java.util.AbstractCollection;
029import java.util.Arrays;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.HashSet;
033import java.util.Iterator;
034import java.util.List;
035import org.checkerframework.checker.nullness.compatqual.NullableDecl;
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  ImmutableCollection() {}
170
171  /** Returns an unmodifiable iterator across the elements in this collection. */
172  @Override
173  public abstract UnmodifiableIterator<E> iterator();
174
175  private static final Object[] EMPTY_ARRAY = {};
176
177  @Override
178  public final Object[] toArray() {
179    return toArray(EMPTY_ARRAY);
180  }
181
182  @CanIgnoreReturnValue
183  @Override
184  public final <T> T[] toArray(T[] other) {
185    checkNotNull(other);
186    int size = size();
187
188    if (other.length < size) {
189      Object[] internal = internalArray();
190      if (internal != null) {
191        return Platform.copy(internal, internalArrayStart(), internalArrayEnd(), other);
192      }
193      other = ObjectArrays.newArray(other, size);
194    } else if (other.length > size) {
195      other[size] = null;
196    }
197    copyIntoArray(other, 0);
198    return other;
199  }
200
201  /** If this collection is backed by an array of its elements in insertion order, returns it. */
202  @NullableDecl
203  Object[] internalArray() {
204    return null;
205  }
206
207  /**
208   * If this collection is backed by an array of its elements in insertion order, returns the offset
209   * where this collection's elements start.
210   */
211  int internalArrayStart() {
212    throw new UnsupportedOperationException();
213  }
214
215  /**
216   * If this collection is backed by an array of its elements in insertion order, returns the offset
217   * where this collection's elements end.
218   */
219  int internalArrayEnd() {
220    throw new UnsupportedOperationException();
221  }
222
223  @Override
224  public abstract boolean contains(@NullableDecl Object object);
225
226  /**
227   * Guaranteed to throw an exception and leave the collection unmodified.
228   *
229   * @throws UnsupportedOperationException always
230   * @deprecated Unsupported operation.
231   */
232  @CanIgnoreReturnValue
233  @Deprecated
234  @Override
235  @DoNotCall("Always throws UnsupportedOperationException")
236  public final boolean add(E e) {
237    throw new UnsupportedOperationException();
238  }
239
240  /**
241   * Guaranteed to throw an exception and leave the collection unmodified.
242   *
243   * @throws UnsupportedOperationException always
244   * @deprecated Unsupported operation.
245   */
246  @CanIgnoreReturnValue
247  @Deprecated
248  @Override
249  @DoNotCall("Always throws UnsupportedOperationException")
250  public final boolean remove(Object object) {
251    throw new UnsupportedOperationException();
252  }
253
254  /**
255   * Guaranteed to throw an exception and leave the collection unmodified.
256   *
257   * @throws UnsupportedOperationException always
258   * @deprecated Unsupported operation.
259   */
260  @CanIgnoreReturnValue
261  @Deprecated
262  @Override
263  @DoNotCall("Always throws UnsupportedOperationException")
264  public final boolean addAll(Collection<? extends E> newElements) {
265    throw new UnsupportedOperationException();
266  }
267
268  /**
269   * Guaranteed to throw an exception and leave the collection unmodified.
270   *
271   * @throws UnsupportedOperationException always
272   * @deprecated Unsupported operation.
273   */
274  @CanIgnoreReturnValue
275  @Deprecated
276  @Override
277  @DoNotCall("Always throws UnsupportedOperationException")
278  public final boolean removeAll(Collection<?> oldElements) {
279    throw new UnsupportedOperationException();
280  }
281
282  /**
283   * Guaranteed to throw an exception and leave the collection unmodified.
284   *
285   * @throws UnsupportedOperationException always
286   * @deprecated Unsupported operation.
287   */
288  @CanIgnoreReturnValue
289  @Deprecated
290  @Override
291  @DoNotCall("Always throws UnsupportedOperationException")
292  public final boolean retainAll(Collection<?> elementsToKeep) {
293    throw new UnsupportedOperationException();
294  }
295
296  /**
297   * Guaranteed to throw an exception and leave the collection unmodified.
298   *
299   * @throws UnsupportedOperationException always
300   * @deprecated Unsupported operation.
301   */
302  @Deprecated
303  @Override
304  @DoNotCall("Always throws UnsupportedOperationException")
305  public final void clear() {
306    throw new UnsupportedOperationException();
307  }
308
309  /**
310   * Returns an {@code ImmutableList} containing the same elements, in the same order, as this
311   * collection.
312   *
313   * <p><b>Performance note:</b> in most cases this method can return quickly without actually
314   * copying anything. The exact circumstances under which the copy is performed are undefined and
315   * subject to change.
316   *
317   * @since 2.0
318   */
319  public ImmutableList<E> asList() {
320    return isEmpty() ? ImmutableList.<E>of() : ImmutableList.<E>asImmutableList(toArray());
321  }
322
323  /**
324   * Returns {@code true} if this immutable collection's implementation contains references to
325   * user-created objects that aren't accessible via this collection's methods. This is generally
326   * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
327   * memory leaks.
328   */
329  abstract boolean isPartialView();
330
331  /**
332   * Copies the contents of this immutable collection into the specified array at the specified
333   * offset. Returns {@code offset + size()}.
334   */
335  @CanIgnoreReturnValue
336  int copyIntoArray(Object[] dst, int offset) {
337    for (E e : this) {
338      dst[offset++] = e;
339    }
340    return offset;
341  }
342
343  Object writeReplace() {
344    // We serialize by default to ImmutableList, the simplest thing that works.
345    return new ImmutableList.SerializedForm(toArray());
346  }
347
348  /**
349   * Abstract base class for builders of {@link ImmutableCollection} types.
350   *
351   * @since 10.0
352   */
353  @DoNotMock
354  public abstract static class Builder<E> {
355    static final int DEFAULT_INITIAL_CAPACITY = 4;
356
357    static int expandedCapacity(int oldCapacity, int minCapacity) {
358      if (minCapacity < 0) {
359        throw new AssertionError("cannot store more than MAX_VALUE elements");
360      }
361      // careful of overflow!
362      int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
363      if (newCapacity < minCapacity) {
364        newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
365      }
366      if (newCapacity < 0) {
367        newCapacity = Integer.MAX_VALUE;
368        // guaranteed to be >= newCapacity
369      }
370      return newCapacity;
371    }
372
373    Builder() {}
374
375    /**
376     * Adds {@code element} to the {@code ImmutableCollection} being built.
377     *
378     * <p>Note that each builder class covariantly returns its own type from this method.
379     *
380     * @param element the element to add
381     * @return this {@code Builder} instance
382     * @throws NullPointerException if {@code element} is null
383     */
384    @CanIgnoreReturnValue
385    public abstract Builder<E> add(E element);
386
387    /**
388     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
389     *
390     * <p>Note that each builder class overrides this method in order to covariantly return its own
391     * type.
392     *
393     * @param elements the elements to add
394     * @return this {@code Builder} instance
395     * @throws NullPointerException if {@code elements} is null or contains a null element
396     */
397    @CanIgnoreReturnValue
398    public Builder<E> add(E... elements) {
399      for (E element : elements) {
400        add(element);
401      }
402      return this;
403    }
404
405    /**
406     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
407     *
408     * <p>Note that each builder class overrides this method in order to covariantly return its own
409     * type.
410     *
411     * @param elements the elements to add
412     * @return this {@code Builder} instance
413     * @throws NullPointerException if {@code elements} is null or contains a null element
414     */
415    @CanIgnoreReturnValue
416    public Builder<E> addAll(Iterable<? extends E> elements) {
417      for (E element : elements) {
418        add(element);
419      }
420      return this;
421    }
422
423    /**
424     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
425     *
426     * <p>Note that each builder class overrides this method in order to covariantly return its own
427     * type.
428     *
429     * @param elements the elements to add
430     * @return this {@code Builder} instance
431     * @throws NullPointerException if {@code elements} is null or contains a null element
432     */
433    @CanIgnoreReturnValue
434    public Builder<E> addAll(Iterator<? extends E> elements) {
435      while (elements.hasNext()) {
436        add(elements.next());
437      }
438      return this;
439    }
440
441    /**
442     * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the
443     * elements provided to this builder.
444     *
445     * <p>Note that each builder class covariantly returns the appropriate type of {@code
446     * ImmutableCollection} from this method.
447     */
448    public abstract ImmutableCollection<E> build();
449  }
450
451  abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> {
452    Object[] contents;
453    int size;
454    boolean forceCopy;
455
456    ArrayBasedBuilder(int initialCapacity) {
457      checkNonnegative(initialCapacity, "initialCapacity");
458      this.contents = new Object[initialCapacity];
459      this.size = 0;
460    }
461
462    /*
463     * Expand the absolute capacity of the builder so it can accept at least the specified number of
464     * elements without being resized. Also, if we've already built a collection backed by the
465     * current array, create a new array.
466     */
467    private void getReadyToExpandTo(int minCapacity) {
468      if (contents.length < minCapacity) {
469        this.contents =
470            Arrays.copyOf(this.contents, expandedCapacity(contents.length, minCapacity));
471        forceCopy = false;
472      } else if (forceCopy) {
473        this.contents = contents.clone();
474        forceCopy = false;
475      }
476    }
477
478    @CanIgnoreReturnValue
479    @Override
480    public ArrayBasedBuilder<E> add(E element) {
481      checkNotNull(element);
482      getReadyToExpandTo(size + 1);
483      contents[size++] = element;
484      return this;
485    }
486
487    @CanIgnoreReturnValue
488    @Override
489    public Builder<E> add(E... elements) {
490      addAll(elements, elements.length);
491      return this;
492    }
493
494    final void addAll(Object[] elements, int n) {
495      checkElementsNotNull(elements, n);
496      getReadyToExpandTo(size + n);
497      System.arraycopy(elements, 0, contents, size, n);
498      size += n;
499    }
500
501    @CanIgnoreReturnValue
502    @Override
503    public Builder<E> addAll(Iterable<? extends E> elements) {
504      if (elements instanceof Collection) {
505        Collection<?> collection = (Collection<?>) elements;
506        getReadyToExpandTo(size + collection.size());
507        if (collection instanceof ImmutableCollection) {
508          ImmutableCollection<?> immutableCollection = (ImmutableCollection<?>) collection;
509          size = immutableCollection.copyIntoArray(contents, size);
510          return this;
511        }
512      }
513      super.addAll(elements);
514      return this;
515    }
516  }
517}