001/* 002 * Copyright (C) 2007 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.checkArgument; 020import static com.google.common.base.Preconditions.checkElementIndex; 021import static com.google.common.base.Preconditions.checkNotNull; 022import static com.google.common.base.Preconditions.checkPositionIndex; 023import static com.google.common.base.Preconditions.checkPositionIndexes; 024import static com.google.common.collect.CollectPreconditions.checkNonnegative; 025import static com.google.common.collect.ObjectArrays.checkElementsNotNull; 026import static com.google.common.collect.RegularImmutableList.EMPTY; 027 028import com.google.common.annotations.Beta; 029import com.google.common.annotations.GwtCompatible; 030import com.google.common.annotations.J2ktIncompatible; 031import com.google.errorprone.annotations.CanIgnoreReturnValue; 032import com.google.errorprone.annotations.DoNotCall; 033import com.google.errorprone.annotations.InlineMe; 034import java.io.InvalidObjectException; 035import java.io.ObjectInputStream; 036import java.io.Serializable; 037import java.util.Arrays; 038import java.util.Collection; 039import java.util.Collections; 040import java.util.Comparator; 041import java.util.Iterator; 042import java.util.List; 043import java.util.RandomAccess; 044import javax.annotation.CheckForNull; 045import org.checkerframework.checker.nullness.qual.Nullable; 046 047/** 048 * A {@link List} whose contents will never change, with many other important properties detailed at 049 * {@link ImmutableCollection}. 050 * 051 * <p>See the Guava User Guide article on <a href= 052 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>. 053 * 054 * @see ImmutableMap 055 * @see ImmutableSet 056 * @author Kevin Bourrillion 057 * @since 2.0 058 */ 059@GwtCompatible(serializable = true, emulated = true) 060@SuppressWarnings("serial") // we're overriding default serialization 061@ElementTypesAreNonnullByDefault 062public abstract class ImmutableList<E> extends ImmutableCollection<E> 063 implements List<E>, RandomAccess { 064 /** 065 * Returns the empty immutable list. This list behaves and performs comparably to {@link 066 * Collections#emptyList}, and is preferable mainly for consistency and maintainability of your 067 * code. 068 * 069 * <p><b>Performance note:</b> the instance returned is a singleton. 070 */ 071 // Casting to any type is safe because the list will never hold any elements. 072 @SuppressWarnings("unchecked") 073 public static <E> ImmutableList<E> of() { 074 return (ImmutableList<E>) EMPTY; 075 } 076 077 /** 078 * Returns an immutable list containing a single element. This list behaves and performs 079 * comparably to {@link Collections#singletonList}, but will not accept a null element. It is 080 * preferable mainly for consistency and maintainability of your code. 081 * 082 * @throws NullPointerException if {@code element} is null 083 */ 084 public static <E> ImmutableList<E> of(E element) { 085 return construct(element); 086 } 087 088 /** 089 * Returns an immutable list containing the given elements, in order. 090 * 091 * @throws NullPointerException if any element is null 092 */ 093 public static <E> ImmutableList<E> of(E e1, E e2) { 094 return construct(e1, e2); 095 } 096 097 /** 098 * Returns an immutable list containing the given elements, in order. 099 * 100 * @throws NullPointerException if any element is null 101 */ 102 public static <E> ImmutableList<E> of(E e1, E e2, E e3) { 103 return construct(e1, e2, e3); 104 } 105 106 /** 107 * Returns an immutable list containing the given elements, in order. 108 * 109 * @throws NullPointerException if any element is null 110 */ 111 public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) { 112 return construct(e1, e2, e3, e4); 113 } 114 115 /** 116 * Returns an immutable list containing the given elements, in order. 117 * 118 * @throws NullPointerException if any element is null 119 */ 120 public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) { 121 return construct(e1, e2, e3, e4, e5); 122 } 123 124 /** 125 * Returns an immutable list containing the given elements, in order. 126 * 127 * @throws NullPointerException if any element is null 128 */ 129 public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) { 130 return construct(e1, e2, e3, e4, e5, e6); 131 } 132 133 /** 134 * Returns an immutable list containing the given elements, in order. 135 * 136 * @throws NullPointerException if any element is null 137 */ 138 public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) { 139 return construct(e1, e2, e3, e4, e5, e6, e7); 140 } 141 142 /** 143 * Returns an immutable list containing the given elements, in order. 144 * 145 * @throws NullPointerException if any element is null 146 */ 147 public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) { 148 return construct(e1, e2, e3, e4, e5, e6, e7, e8); 149 } 150 151 /** 152 * Returns an immutable list containing the given elements, in order. 153 * 154 * @throws NullPointerException if any element is null 155 */ 156 public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) { 157 return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9); 158 } 159 160 /** 161 * Returns an immutable list containing the given elements, in order. 162 * 163 * @throws NullPointerException if any element is null 164 */ 165 public static <E> ImmutableList<E> of( 166 E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) { 167 return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); 168 } 169 170 /** 171 * Returns an immutable list containing the given elements, in order. 172 * 173 * @throws NullPointerException if any element is null 174 */ 175 public static <E> ImmutableList<E> of( 176 E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) { 177 return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); 178 } 179 180 // These go up to eleven. After that, you just get the varargs form, and 181 // whatever warnings might come along with it. :( 182 183 /** 184 * Returns an immutable list containing the given elements, in order. 185 * 186 * <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}. 187 * 188 * @throws NullPointerException if any element is null 189 * @since 3.0 (source-compatible since 2.0) 190 */ 191 @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning. 192 public static <E> ImmutableList<E> of( 193 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) { 194 checkArgument( 195 others.length <= Integer.MAX_VALUE - 12, "the total number of elements must fit in an int"); 196 Object[] array = new Object[12 + others.length]; 197 array[0] = e1; 198 array[1] = e2; 199 array[2] = e3; 200 array[3] = e4; 201 array[4] = e5; 202 array[5] = e6; 203 array[6] = e7; 204 array[7] = e8; 205 array[8] = e9; 206 array[9] = e10; 207 array[10] = e11; 208 array[11] = e12; 209 System.arraycopy(others, 0, array, 12, others.length); 210 return construct(array); 211 } 212 213 /** 214 * Returns an immutable list containing the given elements, in order. If {@code elements} is a 215 * {@link Collection}, this method behaves exactly as {@link #copyOf(Collection)}; otherwise, it 216 * behaves exactly as {@code copyOf(elements.iterator()}. 217 * 218 * @throws NullPointerException if {@code elements} contains a null element 219 */ 220 public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) { 221 checkNotNull(elements); // TODO(kevinb): is this here only for GWT? 222 return (elements instanceof Collection) 223 ? copyOf((Collection<? extends E>) elements) 224 : copyOf(elements.iterator()); 225 } 226 227 /** 228 * Returns an immutable list containing the given elements, in order. 229 * 230 * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 231 * safe to do so. The exact circumstances under which a copy will or will not be performed are 232 * undocumented and subject to change. 233 * 234 * <p>Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)} 235 * returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while 236 * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one element 237 * (the given list itself). 238 * 239 * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent 240 * collection that is currently being modified by another thread. 241 * 242 * @throws NullPointerException if {@code elements} contains a null element 243 */ 244 public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) { 245 if (elements instanceof ImmutableCollection) { 246 @SuppressWarnings("unchecked") // all supported methods are covariant 247 ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList(); 248 return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list; 249 } 250 return construct(elements.toArray()); 251 } 252 253 /** 254 * Returns an immutable list containing the given elements, in order. 255 * 256 * @throws NullPointerException if {@code elements} contains a null element 257 */ 258 public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) { 259 // We special-case for 0 or 1 elements, but going further is madness. 260 if (!elements.hasNext()) { 261 return of(); 262 } 263 E first = elements.next(); 264 if (!elements.hasNext()) { 265 return of(first); 266 } else { 267 return new ImmutableList.Builder<E>().add(first).addAll(elements).build(); 268 } 269 } 270 271 /** 272 * Returns an immutable list containing the given elements, in order. 273 * 274 * @throws NullPointerException if {@code elements} contains a null element 275 * @since 3.0 276 */ 277 public static <E> ImmutableList<E> copyOf(E[] elements) { 278 return (elements.length == 0) 279 ? ImmutableList.<E>of() 280 : ImmutableList.<E>construct(elements.clone()); 281 } 282 283 /** 284 * Returns an immutable list containing the given elements, sorted according to their natural 285 * order. The sorting algorithm used is stable, so elements that compare as equal will stay in the 286 * order in which they appear in the input. 287 * 288 * <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code 289 * ImmutableSortedSet.copyOf(elements)}; if you want a {@code List} you can use its {@code 290 * asList()} view. 291 * 292 * <p><b>Java 8 users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted 293 * {@code ImmutableList}, use {@code stream.sorted().collect(toImmutableList())}. 294 * 295 * @throws NullPointerException if any element in the input is null 296 * @since 21.0 297 */ 298 public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf( 299 Iterable<? extends E> elements) { 300 Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]); 301 checkElementsNotNull((Object[]) array); 302 Arrays.sort(array); 303 return asImmutableList(array); 304 } 305 306 /** 307 * Returns an immutable list containing the given elements, in sorted order relative to the 308 * specified comparator. The sorting algorithm used is stable, so elements that compare as equal 309 * will stay in the order in which they appear in the input. 310 * 311 * <p>If your data has no duplicates, or you wish to deduplicate elements, use {@code 312 * ImmutableSortedSet.copyOf(comparator, elements)}; if you want a {@code List} you can use its 313 * {@code asList()} view. 314 * 315 * <p><b>Java 8 users:</b> If you want to convert a {@link java.util.stream.Stream} to a sorted 316 * {@code ImmutableList}, use {@code stream.sorted(comparator).collect(toImmutableList())}. 317 * 318 * @throws NullPointerException if any element in the input is null 319 * @since 21.0 320 */ 321 public static <E> ImmutableList<E> sortedCopyOf( 322 Comparator<? super E> comparator, Iterable<? extends E> elements) { 323 checkNotNull(comparator); 324 @SuppressWarnings("unchecked") // all supported methods are covariant 325 E[] array = (E[]) Iterables.toArray(elements); 326 checkElementsNotNull(array); 327 Arrays.sort(array, comparator); 328 return asImmutableList(array); 329 } 330 331 /** Views the array as an immutable list. Checks for nulls; does not copy. */ 332 private static <E> ImmutableList<E> construct(Object... elements) { 333 return asImmutableList(checkElementsNotNull(elements)); 334 } 335 336 /** 337 * Views the array as an immutable list. Does not check for nulls; does not copy. 338 * 339 * <p>The array must be internally created. 340 */ 341 static <E> ImmutableList<E> asImmutableList(Object[] elements) { 342 return asImmutableList(elements, elements.length); 343 } 344 345 /** Views the array as an immutable list. Does not check for nulls. */ 346 static <E> ImmutableList<E> asImmutableList(@Nullable Object[] elements, int length) { 347 if (length == 0) { 348 return of(); 349 } 350 return new RegularImmutableList<E>(elements, length); 351 } 352 353 ImmutableList() {} 354 355 // This declaration is needed to make List.iterator() and 356 // ImmutableCollection.iterator() consistent. 357 @Override 358 public UnmodifiableIterator<E> iterator() { 359 return listIterator(); 360 } 361 362 @Override 363 public UnmodifiableListIterator<E> listIterator() { 364 return listIterator(0); 365 } 366 367 @SuppressWarnings("unchecked") 368 @Override 369 public UnmodifiableListIterator<E> listIterator(int index) { 370 checkPositionIndex(index, size()); 371 if (isEmpty()) { 372 return (UnmodifiableListIterator<E>) EMPTY_ITR; 373 } else { 374 return new Itr<E>(this, index); 375 } 376 } 377 378 /** A singleton implementation of iterator() for the empty ImmutableList. */ 379 private static final UnmodifiableListIterator<Object> EMPTY_ITR = 380 new Itr<Object>(RegularImmutableList.EMPTY, 0); 381 382 static class Itr<E> extends AbstractIndexedListIterator<E> { 383 private final ImmutableList<E> list; 384 385 Itr(ImmutableList<E> list, int index) { 386 super(list.size(), index); 387 this.list = list; 388 } 389 390 @Override 391 protected E get(int index) { 392 return list.get(index); 393 } 394 } 395 396 @Override 397 public int indexOf(@CheckForNull Object object) { 398 return (object == null) ? -1 : Lists.indexOfImpl(this, object); 399 } 400 401 @Override 402 public int lastIndexOf(@CheckForNull Object object) { 403 return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object); 404 } 405 406 @Override 407 public boolean contains(@CheckForNull Object object) { 408 return indexOf(object) >= 0; 409 } 410 411 // constrain the return type to ImmutableList<E> 412 413 /** 414 * Returns an immutable list of the elements between the specified {@code fromIndex}, inclusive, 415 * and {@code toIndex}, exclusive. (If {@code fromIndex} and {@code toIndex} are equal, the empty 416 * immutable list is returned.) 417 */ 418 @Override 419 public ImmutableList<E> subList(int fromIndex, int toIndex) { 420 checkPositionIndexes(fromIndex, toIndex, size()); 421 int length = toIndex - fromIndex; 422 if (length == size()) { 423 return this; 424 } else if (length == 0) { 425 return of(); 426 } else { 427 return subListUnchecked(fromIndex, toIndex); 428 } 429 } 430 431 /** 432 * Called by the default implementation of {@link #subList} when {@code toIndex - fromIndex > 1}, 433 * after index validation has already been performed. 434 */ 435 ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) { 436 return new SubList(fromIndex, toIndex - fromIndex); 437 } 438 439 class SubList extends ImmutableList<E> { 440 final transient int offset; 441 final transient int length; 442 443 SubList(int offset, int length) { 444 this.offset = offset; 445 this.length = length; 446 } 447 448 @Override 449 public int size() { 450 return length; 451 } 452 453 @Override 454 @CheckForNull 455 @Nullable 456 Object[] internalArray() { 457 return ImmutableList.this.internalArray(); 458 } 459 460 @Override 461 int internalArrayStart() { 462 return ImmutableList.this.internalArrayStart() + offset; 463 } 464 465 @Override 466 int internalArrayEnd() { 467 return ImmutableList.this.internalArrayStart() + offset + length; 468 } 469 470 @Override 471 public E get(int index) { 472 checkElementIndex(index, length); 473 return ImmutableList.this.get(index + offset); 474 } 475 476 @Override 477 public ImmutableList<E> subList(int fromIndex, int toIndex) { 478 checkPositionIndexes(fromIndex, toIndex, length); 479 return ImmutableList.this.subList(fromIndex + offset, toIndex + offset); 480 } 481 482 @Override 483 boolean isPartialView() { 484 return true; 485 } 486 } 487 488 /** 489 * Guaranteed to throw an exception and leave the list unmodified. 490 * 491 * @throws UnsupportedOperationException always 492 * @deprecated Unsupported operation. 493 */ 494 @CanIgnoreReturnValue 495 @Deprecated 496 @Override 497 @DoNotCall("Always throws UnsupportedOperationException") 498 public final boolean addAll(int index, Collection<? extends E> newElements) { 499 throw new UnsupportedOperationException(); 500 } 501 502 /** 503 * Guaranteed to throw an exception and leave the list unmodified. 504 * 505 * @throws UnsupportedOperationException always 506 * @deprecated Unsupported operation. 507 */ 508 @CanIgnoreReturnValue 509 @Deprecated 510 @Override 511 @DoNotCall("Always throws UnsupportedOperationException") 512 public final E set(int index, E element) { 513 throw new UnsupportedOperationException(); 514 } 515 516 /** 517 * Guaranteed to throw an exception and leave the list unmodified. 518 * 519 * @throws UnsupportedOperationException always 520 * @deprecated Unsupported operation. 521 */ 522 @Deprecated 523 @Override 524 @DoNotCall("Always throws UnsupportedOperationException") 525 public final void add(int index, E element) { 526 throw new UnsupportedOperationException(); 527 } 528 529 /** 530 * Guaranteed to throw an exception and leave the list unmodified. 531 * 532 * @throws UnsupportedOperationException always 533 * @deprecated Unsupported operation. 534 */ 535 @CanIgnoreReturnValue 536 @Deprecated 537 @Override 538 @DoNotCall("Always throws UnsupportedOperationException") 539 public final E remove(int index) { 540 throw new UnsupportedOperationException(); 541 } 542 543 /** 544 * Returns this list instance. 545 * 546 * @since 2.0 547 * @deprecated There is no reason to use this; it always returns {@code this}. 548 */ 549 @InlineMe(replacement = "this") 550 @Deprecated 551 @Override 552 public final ImmutableList<E> asList() { 553 return this; 554 } 555 556 @Override 557 int copyIntoArray(@Nullable Object[] dst, int offset) { 558 // this loop is faster for RandomAccess instances, which ImmutableLists are 559 int size = size(); 560 for (int i = 0; i < size; i++) { 561 dst[offset + i] = get(i); 562 } 563 return offset + size; 564 } 565 566 /** 567 * Returns a view of this immutable list in reverse order. For example, {@code ImmutableList.of(1, 568 * 2, 3).reverse()} is equivalent to {@code ImmutableList.of(3, 2, 1)}. 569 * 570 * @return a view of this immutable list in reverse order 571 * @since 7.0 572 */ 573 public ImmutableList<E> reverse() { 574 return (size() <= 1) ? this : new ReverseImmutableList<E>(this); 575 } 576 577 private static class ReverseImmutableList<E> extends ImmutableList<E> { 578 private final transient ImmutableList<E> forwardList; 579 580 ReverseImmutableList(ImmutableList<E> backingList) { 581 this.forwardList = backingList; 582 } 583 584 private int reverseIndex(int index) { 585 return (size() - 1) - index; 586 } 587 588 private int reversePosition(int index) { 589 return size() - index; 590 } 591 592 @Override 593 public ImmutableList<E> reverse() { 594 return forwardList; 595 } 596 597 @Override 598 public boolean contains(@CheckForNull Object object) { 599 return forwardList.contains(object); 600 } 601 602 @Override 603 public int indexOf(@CheckForNull Object object) { 604 int index = forwardList.lastIndexOf(object); 605 return (index >= 0) ? reverseIndex(index) : -1; 606 } 607 608 @Override 609 public int lastIndexOf(@CheckForNull Object object) { 610 int index = forwardList.indexOf(object); 611 return (index >= 0) ? reverseIndex(index) : -1; 612 } 613 614 @Override 615 public ImmutableList<E> subList(int fromIndex, int toIndex) { 616 checkPositionIndexes(fromIndex, toIndex, size()); 617 return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse(); 618 } 619 620 @Override 621 public E get(int index) { 622 checkElementIndex(index, size()); 623 return forwardList.get(reverseIndex(index)); 624 } 625 626 @Override 627 public int size() { 628 return forwardList.size(); 629 } 630 631 @Override 632 boolean isPartialView() { 633 return forwardList.isPartialView(); 634 } 635 } 636 637 @Override 638 public boolean equals(@CheckForNull Object obj) { 639 return Lists.equalsImpl(this, obj); 640 } 641 642 @Override 643 public int hashCode() { 644 int hashCode = 1; 645 int n = size(); 646 for (int i = 0; i < n; i++) { 647 hashCode = 31 * hashCode + get(i).hashCode(); 648 649 hashCode = ~~hashCode; 650 // needed to deal with GWT integer overflow 651 } 652 return hashCode; 653 } 654 655 /* 656 * Serializes ImmutableLists as their logical contents. This ensures that 657 * implementation types do not leak into the serialized representation. 658 */ 659 @J2ktIncompatible // serialization 660 static class SerializedForm implements Serializable { 661 final Object[] elements; 662 663 SerializedForm(Object[] elements) { 664 this.elements = elements; 665 } 666 667 Object readResolve() { 668 return copyOf(elements); 669 } 670 671 private static final long serialVersionUID = 0; 672 } 673 674 @J2ktIncompatible // serialization 675 private void readObject(ObjectInputStream stream) throws InvalidObjectException { 676 throw new InvalidObjectException("Use SerializedForm"); 677 } 678 679 @Override 680 @J2ktIncompatible // serialization 681 Object writeReplace() { 682 return new SerializedForm(toArray()); 683 } 684 685 /** 686 * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 687 * Builder} constructor. 688 */ 689 public static <E> Builder<E> builder() { 690 return new Builder<E>(); 691 } 692 693 /** 694 * Returns a new builder, expecting the specified number of elements to be added. 695 * 696 * <p>If {@code expectedSize} is exactly the number of elements added to the builder before {@link 697 * Builder#build} is called, the builder is likely to perform better than an unsized {@link 698 * #builder()} would have. 699 * 700 * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, 701 * but not exactly, the number of elements added to the builder. 702 * 703 * @since 23.1 704 */ 705 @Beta 706 public static <E> Builder<E> builderWithExpectedSize(int expectedSize) { 707 checkNonnegative(expectedSize, "expectedSize"); 708 return new ImmutableList.Builder<E>(expectedSize); 709 } 710 711 /** 712 * A builder for creating immutable list instances, especially {@code public static final} lists 713 * ("constant lists"). Example: 714 * 715 * <pre>{@code 716 * public static final ImmutableList<Color> GOOGLE_COLORS 717 * = new ImmutableList.Builder<Color>() 718 * .addAll(WEBSAFE_COLORS) 719 * .add(new Color(0, 191, 255)) 720 * .build(); 721 * }</pre> 722 * 723 * <p>Elements appear in the resulting list in the same order they were added to the builder. 724 * 725 * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build 726 * multiple lists in series. Each new list contains all the elements of the ones created before 727 * it. 728 * 729 * @since 2.0 730 */ 731 public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> { 732 /** 733 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 734 * ImmutableList#builder}. 735 */ 736 public Builder() { 737 this(DEFAULT_INITIAL_CAPACITY); 738 } 739 740 Builder(int capacity) { 741 super(capacity); 742 } 743 744 /** 745 * Adds {@code element} to the {@code ImmutableList}. 746 * 747 * @param element the element to add 748 * @return this {@code Builder} object 749 * @throws NullPointerException if {@code element} is null 750 */ 751 @CanIgnoreReturnValue 752 @Override 753 public Builder<E> add(E element) { 754 super.add(element); 755 return this; 756 } 757 758 /** 759 * Adds each element of {@code elements} to the {@code ImmutableList}. 760 * 761 * @param elements the {@code Iterable} to add to the {@code ImmutableList} 762 * @return this {@code Builder} object 763 * @throws NullPointerException if {@code elements} is null or contains a null element 764 */ 765 @CanIgnoreReturnValue 766 @Override 767 public Builder<E> add(E... elements) { 768 super.add(elements); 769 return this; 770 } 771 772 /** 773 * Adds each element of {@code elements} to the {@code ImmutableList}. 774 * 775 * @param elements the {@code Iterable} to add to the {@code ImmutableList} 776 * @return this {@code Builder} object 777 * @throws NullPointerException if {@code elements} is null or contains a null element 778 */ 779 @CanIgnoreReturnValue 780 @Override 781 public Builder<E> addAll(Iterable<? extends E> elements) { 782 super.addAll(elements); 783 return this; 784 } 785 786 /** 787 * Adds each element of {@code elements} to the {@code ImmutableList}. 788 * 789 * @param elements the {@code Iterator} to add to the {@code ImmutableList} 790 * @return this {@code Builder} object 791 * @throws NullPointerException if {@code elements} is null or contains a null element 792 */ 793 @CanIgnoreReturnValue 794 @Override 795 public Builder<E> addAll(Iterator<? extends E> elements) { 796 super.addAll(elements); 797 return this; 798 } 799 800 @CanIgnoreReturnValue 801 Builder<E> combine(Builder<E> other) { 802 addAll(other.contents, other.size); 803 return this; 804 } 805 806 /** 807 * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder}. 808 */ 809 @Override 810 public ImmutableList<E> build() { 811 forceCopy = true; 812 return asImmutableList(contents, size); 813 } 814 } 815}