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