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