Class ImmutableList.Builder<E>

java.lang.Object
com.google.common.collect.ImmutableCollection.Builder<E>
com.google.common.collect.ImmutableList.Builder<E>
Enclosing class:
ImmutableList<E>

public static final class ImmutableList.Builder<E> extends ImmutableCollection.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();

Elements appear in the resulting list in the same order they were added to the builder.

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
Author:
Kevin Bourrillion
  • Constructor Details

    • Builder

      public Builder()
      Creates a new builder. The returned builder is equivalent to the builder generated by ImmutableList.builder().
  • Method Details

    • add

      @CanIgnoreReturnValue public ImmutableList.Builder<E> add(E element)
      Adds element to the ImmutableList.
      Parameters:
      element - the element to add
      Returns:
      this Builder object
      Throws:
      NullPointerException - if element is null
    • add

      @CanIgnoreReturnValue public ImmutableList.Builder<E> add(E... elements)
      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
    • addAll

      @CanIgnoreReturnValue public ImmutableList.Builder<E> addAll(Iterable<? extends E> elements)
      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
    • addAll

      @CanIgnoreReturnValue public ImmutableList.Builder<E> addAll(Iterator<? extends E> elements)
      Adds each element of elements to the ImmutableList.
      Overrides:
      addAll in class ImmutableCollection.Builder<E>
      Parameters:
      elements - the Iterator to add to the ImmutableList
      Returns:
      this Builder object
      Throws:
      NullPointerException - if elements is null or contains a null element
    • build

      public ImmutableList<E> build()
      Returns a newly-created ImmutableList based on the contents of the Builder.
      Specified by:
      build in class ImmutableCollection.Builder<E>