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