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