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 java.util.Spliterator;
033import java.util.Spliterators;
034import java.util.function.Predicate;
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 9 offers certain immutable collection factory methods, like <a
091 * href="https://docs.oracle.com/javase/9/docs/api/java/util/Set.html#immutable">{@code Set.of}</a>,
092 * we recommend continuing to use these immutable collection classes for this reason.
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@GwtCompatible(emulated = true)
162@SuppressWarnings("serial") // we're overriding default serialization
163// TODO(kevinb): I think we should push everything down to "BaseImmutableCollection" or something,
164// just to do everything we can to emphasize the "practically an interface" nature of this class.
165public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable {
166  /*
167   * We expect SIZED (and SUBSIZED, if applicable) to be added by the spliterator factory methods.
168   * These are properties of the collection as a whole; SIZED and SUBSIZED are more properties of
169   * the spliterator implementation.
170   */
171  static final int SPLITERATOR_CHARACTERISTICS =
172      Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED;
173
174  ImmutableCollection() {}
175
176  /** Returns an unmodifiable iterator across the elements in this collection. */
177  @Override
178  public abstract UnmodifiableIterator<E> iterator();
179
180  @Override
181  public Spliterator<E> spliterator() {
182    return Spliterators.spliterator(this, SPLITERATOR_CHARACTERISTICS);
183  }
184
185  private static final Object[] EMPTY_ARRAY = {};
186
187  @Override
188  public final Object[] toArray() {
189    int size = size();
190    if (size == 0) {
191      return EMPTY_ARRAY;
192    }
193    Object[] result = new Object[size];
194    copyIntoArray(result, 0);
195    return result;
196  }
197
198  @CanIgnoreReturnValue
199  @Override
200  public final <T> T[] toArray(T[] other) {
201    checkNotNull(other);
202    int size = size();
203    if (other.length < size) {
204      other = ObjectArrays.newArray(other, size);
205    } else if (other.length > size) {
206      other[size] = null;
207    }
208    copyIntoArray(other, 0);
209    return other;
210  }
211
212  @Override
213  public abstract boolean contains(@NullableDecl Object object);
214
215  /**
216   * Guaranteed to throw an exception and leave the collection unmodified.
217   *
218   * @throws UnsupportedOperationException always
219   * @deprecated Unsupported operation.
220   */
221  @CanIgnoreReturnValue
222  @Deprecated
223  @Override
224  public final boolean add(E e) {
225    throw new UnsupportedOperationException();
226  }
227
228  /**
229   * Guaranteed to throw an exception and leave the collection unmodified.
230   *
231   * @throws UnsupportedOperationException always
232   * @deprecated Unsupported operation.
233   */
234  @CanIgnoreReturnValue
235  @Deprecated
236  @Override
237  public final boolean remove(Object object) {
238    throw new UnsupportedOperationException();
239  }
240
241  /**
242   * Guaranteed to throw an exception and leave the collection unmodified.
243   *
244   * @throws UnsupportedOperationException always
245   * @deprecated Unsupported operation.
246   */
247  @CanIgnoreReturnValue
248  @Deprecated
249  @Override
250  public final boolean addAll(Collection<? extends E> newElements) {
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  public final boolean removeAll(Collection<?> oldElements) {
264    throw new UnsupportedOperationException();
265  }
266
267  /**
268   * Guaranteed to throw an exception and leave the collection unmodified.
269   *
270   * @throws UnsupportedOperationException always
271   * @deprecated Unsupported operation.
272   */
273  @CanIgnoreReturnValue
274  @Deprecated
275  @Override
276  public final boolean removeIf(Predicate<? super E> filter) {
277    throw new UnsupportedOperationException();
278  }
279
280  /**
281   * Guaranteed to throw an exception and leave the collection unmodified.
282   *
283   * @throws UnsupportedOperationException always
284   * @deprecated Unsupported operation.
285   */
286  @Deprecated
287  @Override
288  public final boolean retainAll(Collection<?> elementsToKeep) {
289    throw new UnsupportedOperationException();
290  }
291
292  /**
293   * Guaranteed to throw an exception and leave the collection unmodified.
294   *
295   * @throws UnsupportedOperationException always
296   * @deprecated Unsupported operation.
297   */
298  @Deprecated
299  @Override
300  public final void clear() {
301    throw new UnsupportedOperationException();
302  }
303
304  /**
305   * Returns an {@code ImmutableList} containing the same elements, in the same order, as this
306   * collection.
307   *
308   * <p><b>Performance note:</b> in most cases this method can return quickly without actually
309   * copying anything. The exact circumstances under which the copy is performed are undefined and
310   * subject to change.
311   *
312   * @since 2.0
313   */
314  public ImmutableList<E> asList() {
315    switch (size()) {
316      case 0:
317        return ImmutableList.of();
318      case 1:
319        return ImmutableList.of(iterator().next());
320      default:
321        return new RegularImmutableAsList<E>(this, toArray());
322    }
323  }
324
325  /**
326   * Returns {@code true} if this immutable collection's implementation contains references to
327   * user-created objects that aren't accessible via this collection's methods. This is generally
328   * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
329   * memory leaks.
330   */
331  abstract boolean isPartialView();
332
333  /**
334   * Copies the contents of this immutable collection into the specified array at the specified
335   * offset. Returns {@code offset + size()}.
336   */
337  @CanIgnoreReturnValue
338  int copyIntoArray(Object[] dst, int offset) {
339    for (E e : this) {
340      dst[offset++] = e;
341    }
342    return offset;
343  }
344
345  Object writeReplace() {
346    // We serialize by default to ImmutableList, the simplest thing that works.
347    return new ImmutableList.SerializedForm(toArray());
348  }
349
350  /**
351   * Abstract base class for builders of {@link ImmutableCollection} types.
352   *
353   * @since 10.0
354   */
355  public abstract static class Builder<E> {
356    static final int DEFAULT_INITIAL_CAPACITY = 4;
357
358    static int expandedCapacity(int oldCapacity, int minCapacity) {
359      if (minCapacity < 0) {
360        throw new AssertionError("cannot store more than MAX_VALUE elements");
361      }
362      // careful of overflow!
363      int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
364      if (newCapacity < minCapacity) {
365        newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
366      }
367      if (newCapacity < 0) {
368        newCapacity = Integer.MAX_VALUE;
369        // guaranteed to be >= newCapacity
370      }
371      return newCapacity;
372    }
373
374    Builder() {}
375
376    /**
377     * Adds {@code element} to the {@code ImmutableCollection} being built.
378     *
379     * <p>Note that each builder class covariantly returns its own type from this method.
380     *
381     * @param element the element to add
382     * @return this {@code Builder} instance
383     * @throws NullPointerException if {@code element} is null
384     */
385    @CanIgnoreReturnValue
386    public abstract Builder<E> add(E element);
387
388    /**
389     * Adds each element of {@code elements} to the {@code ImmutableCollection} being built.
390     *
391     * <p>Note that each builder class overrides this method in order to covariantly return its own
392     * type.
393     *
394     * @param elements the elements to add
395     * @return this {@code Builder} instance
396     * @throws NullPointerException if {@code elements} is null or contains a null element
397     */
398    @CanIgnoreReturnValue
399    public Builder<E> add(E... elements) {
400      for (E element : elements) {
401        add(element);
402      }
403      return this;
404    }
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> addAll(Iterable<? extends 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(Iterator<? extends E> elements) {
436      while (elements.hasNext()) {
437        add(elements.next());
438      }
439      return this;
440    }
441
442    /**
443     * Returns a newly-created {@code ImmutableCollection} of the appropriate type, containing the
444     * elements provided to this builder.
445     *
446     * <p>Note that each builder class covariantly returns the appropriate type of {@code
447     * ImmutableCollection} from this method.
448     */
449    public abstract ImmutableCollection<E> build();
450  }
451
452  abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> {
453    Object[] contents;
454    int size;
455    boolean forceCopy;
456
457    ArrayBasedBuilder(int initialCapacity) {
458      checkNonnegative(initialCapacity, "initialCapacity");
459      this.contents = new Object[initialCapacity];
460      this.size = 0;
461    }
462
463    /*
464     * Expand the absolute capacity of the builder so it can accept at least the specified number of
465     * elements without being resized. Also, if we've already built a collection backed by the
466     * current array, create a new array.
467     */
468    private void getReadyToExpandTo(int minCapacity) {
469      if (contents.length < minCapacity) {
470        this.contents =
471            Arrays.copyOf(this.contents, expandedCapacity(contents.length, minCapacity));
472        forceCopy = false;
473      } else if (forceCopy) {
474        this.contents = contents.clone();
475        forceCopy = false;
476      }
477    }
478
479    @CanIgnoreReturnValue
480    @Override
481    public ArrayBasedBuilder<E> add(E element) {
482      checkNotNull(element);
483      getReadyToExpandTo(size + 1);
484      contents[size++] = element;
485      return this;
486    }
487
488    @CanIgnoreReturnValue
489    @Override
490    public Builder<E> add(E... elements) {
491      checkElementsNotNull(elements);
492      getReadyToExpandTo(size + elements.length);
493      System.arraycopy(elements, 0, contents, size, elements.length);
494      size += elements.length;
495      return this;
496    }
497
498    @CanIgnoreReturnValue
499    @Override
500    public Builder<E> addAll(Iterable<? extends E> elements) {
501      if (elements instanceof Collection) {
502        Collection<?> collection = (Collection<?>) elements;
503        getReadyToExpandTo(size + collection.size());
504        if (collection instanceof ImmutableCollection) {
505          ImmutableCollection<?> immutableCollection = (ImmutableCollection<?>) collection;
506          size = immutableCollection.copyIntoArray(contents, size);
507          return this;
508        }
509      }
510      super.addAll(elements);
511      return this;
512    }
513
514    @CanIgnoreReturnValue
515    ArrayBasedBuilder<E> combine(ArrayBasedBuilder<E> builder) {
516      checkNotNull(builder);
517      getReadyToExpandTo(size + builder.size);
518      System.arraycopy(builder.contents, 0, this.contents, size, builder.size);
519      size += builder.size;
520      return this;
521    }
522  }
523}