Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkElementIndex;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkPositionIndexes;
 import static com.google.common.collect.ObjectArrays.arraysCopyOf;
 import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
 
 
 import java.util.List;
 
 import  javax.annotation.Nullable;

A high-performance, immutable, random-access List implementation. Does not permit null elements.

Unlike Collections.unmodifiableList, which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change. ImmutableList is convenient for public static final lists ("constant lists") and also lets you easily make a "defensive copy" of a list provided to your class by a caller.

Note: Although this class is not final, it cannot be subclassed as it has no public or protected constructors. Thus, instances of this type are guaranteed to be immutable.

See the Guava User Guide article on immutable collections.

Author(s):
Kevin Bourrillion
Since:
2.0 (imported from Google Collections Library)
See also:
ImmutableMap
ImmutableSet
 
 @GwtCompatible(serializable = true, emulated = true)
 @SuppressWarnings("serial"// we're overriding default serialization
 public abstract class ImmutableList<E> extends ImmutableCollection<E>
     implements List<E>, RandomAccess {
 
   private static final ImmutableList<ObjectEMPTY =
Returns the empty immutable list. This set behaves and performs comparably to Collections.emptyList, and is preferable mainly for consistency and maintainability of your code.
 
   // Casting to any type is safe because the list will never hold any elements.
   @SuppressWarnings("unchecked")
   public static <E> ImmutableList<E> of() {
     return (ImmutableList<E>) ;
   }

  
Returns an immutable list containing a single element. This list behaves and performs comparably to Collections.singleton, but will not accept a null element. It is preferable mainly for consistency and maintainability of your code.

Throws:
NullPointerException if element is null
 
   public static <E> ImmutableList<E> of(E element) {
     return new SingletonImmutableList<E>(element);
   }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
 
   public static <E> ImmutableList<E> of(E e1, E e2) {
     return construct(e1e2);
   }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
    return construct(e1e2e3);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
    return construct(e1e2e3e4);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
    return construct(e1e2e3e4e5);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
    return construct(e1e2e3e4e5e6);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
    return construct(e1e2e3e4e5e6e7);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
    return construct(e1e2e3e4e5e6e7e8);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
    return construct(e1e2e3e4e5e6e7e8e9);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
    return construct(e1e2e3e4e5e6e7e8e9e10);
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
    return construct(e1e2e3e4e5e6e7e8e9e10e11);
  }
  // These go up to eleven. After that, you just get the varargs form, and
  // whatever warnings might come along with it. :(

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any element is null
Since:
3.0 (source-compatible since 2.0)
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12,
      E... others) {
    Object[] array = new Object[12 + others.length];
    array[0] = e1;
    array[1] = e2;
    array[2] = e3;
    array[3] = e4;
    array[4] = e5;
    array[5] = e6;
    array[6] = e7;
    array[7] = e8;
    array[8] = e9;
    array[9] = e10;
    array[10] = e11;
    array[11] = e12;
    System.arraycopy(others, 0, array, 12, others.length);
    return construct(array);
  }

  
Returns an immutable list containing the given elements, in order. If elements is a Collection, this method behaves exactly as copyOf(Collection); otherwise, it behaves exactly as copyOf(elements.iterator().

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
    checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
    return (elements instanceof Collection)
      ? copyOf(Collections2.cast(elements))
      : copyOf(elements.iterator());
  }

  
Returns an immutable list containing the given elements, in order.

Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change.

Note that if list is a List<String>, then ImmutableList.copyOf(list) returns an ImmutableList<String> containing each of the strings in list, while ImmutableList.of(list)} returns an ImmutableList<List<String>> containing one element (the given list itself).

This method is safe to use even when elements is a synchronized or concurrent collection that is currently being modified by another thread.

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
    if (elements instanceof ImmutableCollection) {
      @SuppressWarnings("unchecked"// all supported methods are covariant
      ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
      return list.isPartialView()
          ? ImmutableList.<E>asImmutableList(list.toArray())
          : list;
    }
    return construct(elements.toArray());
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
    // We special-case for 0 or 1 elements, but going further is madness.
    if (!elements.hasNext()) {
      return of();
    }
    E first = elements.next();
    if (!elements.hasNext()) {
      return of(first);
    } else {
      return new ImmutableList.Builder<E>()
          .add(first)
          .addAll(elements)
          .build();
    }
  }

  
Returns an immutable list containing the given elements, in order.

Throws:
NullPointerException if any of elements is null
Since:
3.0
  public static <E> ImmutableList<E> copyOf(E[] elements) {
    switch (elements.length) {
      case 0:
        return ImmutableList.of();
      case 1:
        return new SingletonImmutableList<E>(elements[0]);
      default:
        return new RegularImmutableList<E>(checkElementsNotNull(elements.clone()));
    }
  }

  
Views the array as an immutable list. Checks for nulls; does not copy.
  private static <E> ImmutableList<E> construct(Object... elements) {
    return asImmutableList(checkElementsNotNull(elements));
  }

  
Views the array as an immutable list. Does not check for nulls; does not copy.

The array must be internally created.

  static <E> ImmutableList<E> asImmutableList(Object[] elements) {
    return asImmutableList(elementselements.length);
  }

  
Views the array as an immutable list. Copies if the specified range does not cover the complete array. Does not check for nulls.
  static <E> ImmutableList<E> asImmutableList(Object[] elementsint length) {
    switch (length) {
      case 0:
        return of();
      case 1:
        @SuppressWarnings("unchecked"// collection had only Es in it
        ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
        return list;
      default:
        if (length < elements.length) {
          elements = arraysCopyOf(elementslength);
        }
        return new RegularImmutableList<E>(elements);
    }
  }
  // This declaration is needed to make List.iterator() and
  // ImmutableCollection.iterator() consistent.
    return listIterator();
  }
    return listIterator(0);
  }
  @Override public UnmodifiableListIterator<E> listIterator(int index) {
    return new AbstractIndexedListIterator<E>(size(), index) {
      @Override
      protected E get(int index) {
        return ImmutableList.this.get(index);
      }
    };
  }
  public int indexOf(@Nullable Object object) {
    return (object == null) ? -1 : Lists.indexOfImpl(thisobject);
  }
  public int lastIndexOf(@Nullable Object object) {
    return (object == null) ? -1 : Lists.lastIndexOfImpl(thisobject);
  }
  public boolean contains(@Nullable Object object) {
    return indexOf(object) >= 0;
  }
  // constrain the return type to ImmutableList<E>

  
Returns an immutable list of the elements between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the empty immutable list is returned.)
  public ImmutableList<E> subList(int fromIndexint toIndex) {
    checkPositionIndexes(fromIndextoIndexsize());
    int length = toIndex - fromIndex;
    switch (length) {
      case 0:
        return of();
      case 1:
        return of(get(fromIndex));
      default:
        return subListUnchecked(fromIndextoIndex);
    }
  }

  
Called by the default implementation of subList when toIndex - fromIndex > 1, after index validation has already been performed.
  ImmutableList<E> subListUnchecked(int fromIndexint toIndex) {
    return new SubList(fromIndextoIndex - fromIndex);
  }
  class SubList extends ImmutableList<E> {
    transient final int offset;
    transient final int length;
    SubList(int offsetint length) {
      this. = offset;
      this. = length;
    }
    @Override
    public int size() {
      return ;
    }
    @Override
    public E get(int index) {
      checkElementIndex(index);
      return ImmutableList.this.get(index + );
    }
    @Override
    public ImmutableList<E> subList(int fromIndexint toIndex) {
      checkPositionIndexes(fromIndextoIndex);
      return ImmutableList.this.subList(fromIndex + toIndex + );
    }
    @Override
    boolean isPartialView() {
      return true;
    }
  }

  
Guaranteed to throw an exception and leave the list unmodified.

Deprecated:
Unsupported operation.
Throws:
UnsupportedOperationException always
  public final boolean addAll(int indexCollection<? extends E> newElements) {
    throw new UnsupportedOperationException();
  }

  
Guaranteed to throw an exception and leave the list unmodified.

Deprecated:
Unsupported operation.
Throws:
UnsupportedOperationException always
  public final E set(int index, E element) {
    throw new UnsupportedOperationException();
  }

  
Guaranteed to throw an exception and leave the list unmodified.

Deprecated:
Unsupported operation.
Throws:
UnsupportedOperationException always
  public final void add(int index, E element) {
    throw new UnsupportedOperationException();
  }

  
Guaranteed to throw an exception and leave the list unmodified.

Deprecated:
Unsupported operation.
Throws:
UnsupportedOperationException always
  public final E remove(int index) {
    throw new UnsupportedOperationException();
  }

  
Returns this list instance.

Since:
2.0
  @Override public final ImmutableList<E> asList() {
    return this;
  }
  int copyIntoArray(Object[] dstint offset) {
    // this loop is faster for RandomAccess instances, which ImmutableLists are
    int size = size();
    for (int i = 0; i < sizei++) {
      dst[offset + i] = get(i);
    }
    return offset + size;
  }

  
Returns a view of this immutable list in reverse order. For example, ImmutableList.of(1, 2, 3).reverse() is equivalent to ImmutableList.of(3, 2, 1).

Returns:
a view of this immutable list in reverse order
Since:
7.0
  public ImmutableList<E> reverse() {
    return new ReverseImmutableList<E>(this);
  }
  private static class ReverseImmutableList<E> extends ImmutableList<E> {
    private final transient ImmutableList<E> forwardList;
    ReverseImmutableList(ImmutableList<E> backingList) {
      this. = backingList;
    }
    private int reverseIndex(int index) {
      return (size() - 1) - index;
    }
    private int reversePosition(int index) {
      return size() - index;
    }
    @Override public ImmutableList<E> reverse() {
      return ;
    }
    @Override public boolean contains(@Nullable Object object) {
      return .contains(object);
    }
    @Override public int indexOf(@Nullable Object object) {
      int index = .lastIndexOf(object);
      return (index >= 0) ? reverseIndex(index) : -1;
    }
    @Override public int lastIndexOf(@Nullable Object object) {
      int index = .indexOf(object);
      return (index >= 0) ? reverseIndex(index) : -1;
    }
    @Override public ImmutableList<E> subList(int fromIndexint toIndex) {
      checkPositionIndexes(fromIndextoIndexsize());
      return .subList(
          reversePosition(toIndex), reversePosition(fromIndex)).reverse();
    }
    @Override public E get(int index) {
      checkElementIndex(indexsize());
      return .get(reverseIndex(index));
    }
    @Override public int size() {
      return .size();
    }
    @Override boolean isPartialView() {
      return .isPartialView();
    }
  }
  @Override public boolean equals(@Nullable Object obj) {
    return Lists.equalsImpl(thisobj);
  }
  @Override public int hashCode() {
    int hashCode = 1;
    int n = size();
    for (int i = 0; i < ni++) {
      hashCode = 31 * hashCode + get(i).hashCode();
      hashCode = ~~hashCode;
      // needed to deal with GWT integer overflow
    }
    return hashCode;
  }
  /*
   * Serializes ImmutableLists as their logical contents. This ensures that
   * implementation types do not leak into the serialized representation.
   */
  static class SerializedForm implements Serializable {
    final Object[] elements;
    SerializedForm(Object[] elements) {
      this. = elements;
    }
    Object readResolve() {
      return copyOf();
    }
    private static final long serialVersionUID = 0;
  }
  private void readObject(ObjectInputStream stream)
      throws InvalidObjectException {
    throw new InvalidObjectException("Use SerializedForm");
  }
    return new SerializedForm(toArray());
  }

  
Returns a new builder. The generated builder is equivalent to the builder created by the Builder constructor.
  public static <E> Builder<E> builder() {
    return new Builder<E>();
  }

  
A builder for creating immutable list instances, especially public static final lists ("constant lists"). Example:
   public static final ImmutableList<Color> GOOGLE_COLORS
       = new ImmutableList.Builder<Color>()
           .addAll(WEBSAFE_COLORS)
           .add(new Color(0, 191, 255))
           .build();

Builder instances can be reused; it is safe to call build multiple times to build multiple lists in series. Each new list contains all the elements of the ones created before it.

Since:
2.0 (imported from Google Collections Library)
  public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> {
    
Creates a new builder. The returned builder is equivalent to the builder generated by ImmutableList.builder.
    public Builder() {
      this();
    }
    // TODO(user): consider exposing this
    Builder(int capacity) {
      super(capacity);
    }

    
Adds element to the ImmutableList.

Parameters:
element the element to add
Returns:
this Builder object
Throws:
NullPointerException if element is null
    @Override public Builder<E> add(E element) {
      super.add(element);
      return this;
    }

    
Adds each element of elements to the ImmutableList.

Parameters:
elements the Iterable to add to the ImmutableList
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> addAll(Iterable<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    
Adds each element of elements to the ImmutableList.

Parameters:
elements the Iterable to add to the ImmutableList
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> add(E... elements) {
      super.add(elements);
      return this;
    }

    
Adds each element of elements to the ImmutableList.

Parameters:
elements the Iterable to add to the ImmutableList
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    
Returns a newly-created ImmutableList based on the contents of the Builder.
    @Override public ImmutableList<E> build() {
      return asImmutableList();
    }
  }
New to GrepCode? Check out our FAQ X