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