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