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