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