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