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.base.Preconditions.checkState; 025import static com.google.common.collect.CollectPreconditions.checkNonnegative; 026import static com.google.common.collect.CollectPreconditions.checkRemove; 027 028import com.google.common.annotations.GwtCompatible; 029import com.google.common.annotations.GwtIncompatible; 030import com.google.common.annotations.J2ktIncompatible; 031import com.google.common.annotations.VisibleForTesting; 032import com.google.common.base.Function; 033import com.google.common.base.Objects; 034import com.google.common.math.IntMath; 035import com.google.common.primitives.Ints; 036import java.io.Serializable; 037import java.math.RoundingMode; 038import java.util.AbstractList; 039import java.util.AbstractSequentialList; 040import java.util.ArrayList; 041import java.util.Arrays; 042import java.util.Collection; 043import java.util.Collections; 044import java.util.Iterator; 045import java.util.LinkedList; 046import java.util.List; 047import java.util.ListIterator; 048import java.util.NoSuchElementException; 049import java.util.RandomAccess; 050import java.util.concurrent.CopyOnWriteArrayList; 051import javax.annotation.CheckForNull; 052import org.checkerframework.checker.nullness.qual.Nullable; 053 054/** 055 * Static utility methods pertaining to {@link List} instances. Also see this class's counterparts 056 * {@link Sets}, {@link Maps} and {@link Queues}. 057 * 058 * <p>See the Guava User Guide article on <a href= 059 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#lists">{@code Lists}</a>. 060 * 061 * @author Kevin Bourrillion 062 * @author Mike Bostock 063 * @author Louis Wasserman 064 * @since 2.0 065 */ 066@GwtCompatible(emulated = true) 067@ElementTypesAreNonnullByDefault 068public final class Lists { 069 private Lists() {} 070 071 // ArrayList 072 073 /** 074 * Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier). 075 * 076 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableList#of()} instead. 077 * 078 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 079 * use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} directly, taking 080 * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. 081 */ 082 @GwtCompatible(serializable = true) 083 public static <E extends @Nullable Object> ArrayList<E> newArrayList() { 084 return new ArrayList<>(); 085 } 086 087 /** 088 * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements. 089 * 090 * <p><b>Note:</b> essentially the only reason to use this method is when you will need to add or 091 * remove elements later. Otherwise, for non-null elements use {@link ImmutableList#of()} (for 092 * varargs) or {@link ImmutableList#copyOf(Object[])} (for an array) instead. If any elements 093 * might be null, or you need support for {@link List#set(int, Object)}, use {@link 094 * Arrays#asList}. 095 * 096 * <p>Note that even when you do need the ability to add or remove, this method provides only a 097 * tiny bit of syntactic sugar for {@code newArrayList(}{@link Arrays#asList asList}{@code 098 * (...))}, or for creating an empty list then calling {@link Collections#addAll}. This method is 099 * not actually very useful and will likely be deprecated in the future. 100 */ 101 @SafeVarargs 102 @GwtCompatible(serializable = true) 103 public static <E extends @Nullable Object> ArrayList<E> newArrayList(E... elements) { 104 checkNotNull(elements); // for GWT 105 // Avoid integer overflow when a large array is passed in 106 int capacity = computeArrayListCapacity(elements.length); 107 ArrayList<E> list = new ArrayList<>(capacity); 108 Collections.addAll(list, elements); 109 return list; 110 } 111 112 /** 113 * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin 114 * shortcut for creating an empty list then calling {@link Iterables#addAll}. 115 * 116 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link 117 * ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link 118 * FluentIterable} and call {@code elements.toList()}.) 119 * 120 * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use 121 * the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection) constructor} directly, taking 122 * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. 123 */ 124 @GwtCompatible(serializable = true) 125 public static <E extends @Nullable Object> ArrayList<E> newArrayList( 126 Iterable<? extends E> elements) { 127 checkNotNull(elements); // for GWT 128 // Let ArrayList's sizing logic work, if possible 129 return (elements instanceof Collection) 130 ? new ArrayList<>((Collection<? extends E>) elements) 131 : newArrayList(elements.iterator()); 132 } 133 134 /** 135 * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin 136 * shortcut for creating an empty list and then calling {@link Iterators#addAll}. 137 * 138 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link 139 * ImmutableList#copyOf(Iterator)} instead. 140 */ 141 @GwtCompatible(serializable = true) 142 public static <E extends @Nullable Object> ArrayList<E> newArrayList( 143 Iterator<? extends E> elements) { 144 ArrayList<E> list = newArrayList(); 145 Iterators.addAll(list, elements); 146 return list; 147 } 148 149 @VisibleForTesting 150 static int computeArrayListCapacity(int arraySize) { 151 checkNonnegative(arraySize, "arraySize"); 152 153 // TODO(kevinb): Figure out the right behavior, and document it 154 return Ints.saturatedCast(5L + arraySize + (arraySize / 10)); 155 } 156 157 /** 158 * Creates an {@code ArrayList} instance backed by an array with the specified initial size; 159 * simply delegates to {@link ArrayList#ArrayList(int)}. 160 * 161 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 162 * use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly, taking 163 * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. (Unlike here, there is no risk 164 * of overload ambiguity, since the {@code ArrayList} constructors very wisely did not accept 165 * varargs.) 166 * 167 * @param initialArraySize the exact size of the initial backing array for the returned array list 168 * ({@code ArrayList} documentation calls this value the "capacity") 169 * @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size 170 * reaches {@code initialArraySize + 1} 171 * @throws IllegalArgumentException if {@code initialArraySize} is negative 172 */ 173 @GwtCompatible(serializable = true) 174 public static <E extends @Nullable Object> ArrayList<E> newArrayListWithCapacity( 175 int initialArraySize) { 176 checkNonnegative(initialArraySize, "initialArraySize"); // for GWT. 177 return new ArrayList<>(initialArraySize); 178 } 179 180 /** 181 * Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an 182 * unspecified amount of padding; you almost certainly mean to call {@link 183 * #newArrayListWithCapacity} (see that method for further advice on usage). 184 * 185 * <p><b>Note:</b> This method will soon be deprecated. Even in the rare case that you do want 186 * some amount of padding, it's best if you choose your desired amount explicitly. 187 * 188 * @param estimatedSize an estimate of the eventual {@link List#size()} of the new list 189 * @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of 190 * elements 191 * @throws IllegalArgumentException if {@code estimatedSize} is negative 192 */ 193 @GwtCompatible(serializable = true) 194 public static <E extends @Nullable Object> ArrayList<E> newArrayListWithExpectedSize( 195 int estimatedSize) { 196 return new ArrayList<>(computeArrayListCapacity(estimatedSize)); 197 } 198 199 // LinkedList 200 201 /** 202 * Creates a <i>mutable</i>, empty {@code LinkedList} instance (for Java 6 and earlier). 203 * 204 * <p><b>Note:</b> if you won't be adding any elements to the list, use {@link ImmutableList#of()} 205 * instead. 206 * 207 * <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently 208 * outperform {@code LinkedList} except in certain rare and specific situations. Unless you have 209 * spent a lot of time benchmarking your specific needs, use one of those instead. 210 * 211 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 212 * use the {@code LinkedList} {@linkplain LinkedList#LinkedList() constructor} directly, taking 213 * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. 214 */ 215 @GwtCompatible(serializable = true) 216 public static <E extends @Nullable Object> LinkedList<E> newLinkedList() { 217 return new LinkedList<>(); 218 } 219 220 /** 221 * Creates a <i>mutable</i> {@code LinkedList} instance containing the given elements; a very thin 222 * shortcut for creating an empty list then calling {@link Iterables#addAll}. 223 * 224 * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link 225 * ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link 226 * FluentIterable} and call {@code elements.toList()}.) 227 * 228 * <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently 229 * outperform {@code LinkedList} except in certain rare and specific situations. Unless you have 230 * spent a lot of time benchmarking your specific needs, use one of those instead. 231 * 232 * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use 233 * the {@code LinkedList} {@linkplain LinkedList#LinkedList(Collection) constructor} directly, 234 * taking advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. 235 */ 236 @GwtCompatible(serializable = true) 237 public static <E extends @Nullable Object> LinkedList<E> newLinkedList( 238 Iterable<? extends E> elements) { 239 LinkedList<E> list = newLinkedList(); 240 Iterables.addAll(list, elements); 241 return list; 242 } 243 244 /** 245 * Creates an empty {@code CopyOnWriteArrayList} instance. 246 * 247 * <p><b>Note:</b> if you need an immutable empty {@link List}, use {@link Collections#emptyList} 248 * instead. 249 * 250 * @return a new, empty {@code CopyOnWriteArrayList} 251 * @since 12.0 252 */ 253 @J2ktIncompatible 254 @GwtIncompatible // CopyOnWriteArrayList 255 public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() { 256 return new CopyOnWriteArrayList<>(); 257 } 258 259 /** 260 * Creates a {@code CopyOnWriteArrayList} instance containing the given elements. 261 * 262 * @param elements the elements that the list should contain, in order 263 * @return a new {@code CopyOnWriteArrayList} containing those elements 264 * @since 12.0 265 */ 266 @J2ktIncompatible 267 @GwtIncompatible // CopyOnWriteArrayList 268 public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList( 269 Iterable<? extends E> elements) { 270 // We copy elements to an ArrayList first, rather than incurring the 271 // quadratic cost of adding them to the COWAL directly. 272 Collection<? extends E> elementsCollection = 273 (elements instanceof Collection) 274 ? (Collection<? extends E>) elements 275 : newArrayList(elements); 276 return new CopyOnWriteArrayList<>(elementsCollection); 277 } 278 279 /** 280 * Returns an unmodifiable list containing the specified first element and backed by the specified 281 * array of additional elements. Changes to the {@code rest} array will be reflected in the 282 * returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable. 283 * 284 * <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo, 285 * Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum argument count. 286 * 287 * <p>The returned list is serializable and implements {@link RandomAccess}. 288 * 289 * @param first the first element 290 * @param rest an array of additional elements, possibly empty 291 * @return an unmodifiable list containing the specified elements 292 */ 293 public static <E extends @Nullable Object> List<E> asList(@ParametricNullness E first, E[] rest) { 294 return new OnePlusArrayList<>(first, rest); 295 } 296 297 /** 298 * Returns an unmodifiable list containing the specified first and second element, and backed by 299 * the specified array of additional elements. Changes to the {@code rest} array will be reflected 300 * in the returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable. 301 * 302 * <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo, 303 * Foo secondFoo, Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum 304 * argument count. 305 * 306 * <p>The returned list is serializable and implements {@link RandomAccess}. 307 * 308 * @param first the first element 309 * @param second the second element 310 * @param rest an array of additional elements, possibly empty 311 * @return an unmodifiable list containing the specified elements 312 */ 313 public static <E extends @Nullable Object> List<E> asList( 314 @ParametricNullness E first, @ParametricNullness E second, E[] rest) { 315 return new TwoPlusArrayList<>(first, second, rest); 316 } 317 318 /** @see Lists#asList(Object, Object[]) */ 319 private static class OnePlusArrayList<E extends @Nullable Object> extends AbstractList<E> 320 implements Serializable, RandomAccess { 321 @ParametricNullness final E first; 322 final E[] rest; 323 324 OnePlusArrayList(@ParametricNullness E first, E[] rest) { 325 this.first = first; 326 this.rest = checkNotNull(rest); 327 } 328 329 @Override 330 public int size() { 331 return IntMath.saturatedAdd(rest.length, 1); 332 } 333 334 @Override 335 @ParametricNullness 336 public E get(int index) { 337 // check explicitly so the IOOBE will have the right message 338 checkElementIndex(index, size()); 339 return (index == 0) ? first : rest[index - 1]; 340 } 341 342 @J2ktIncompatible private static final long serialVersionUID = 0; 343 } 344 345 /** @see Lists#asList(Object, Object, Object[]) */ 346 private static class TwoPlusArrayList<E extends @Nullable Object> extends AbstractList<E> 347 implements Serializable, RandomAccess { 348 @ParametricNullness final E first; 349 @ParametricNullness final E second; 350 final E[] rest; 351 352 TwoPlusArrayList(@ParametricNullness E first, @ParametricNullness E second, E[] rest) { 353 this.first = first; 354 this.second = second; 355 this.rest = checkNotNull(rest); 356 } 357 358 @Override 359 public int size() { 360 return IntMath.saturatedAdd(rest.length, 2); 361 } 362 363 @Override 364 @ParametricNullness 365 public E get(int index) { 366 switch (index) { 367 case 0: 368 return first; 369 case 1: 370 return second; 371 default: 372 // check explicitly so the IOOBE will have the right message 373 checkElementIndex(index, size()); 374 return rest[index - 2]; 375 } 376 } 377 378 @J2ktIncompatible private static final long serialVersionUID = 0; 379 } 380 381 /** 382 * Returns every possible list that can be formed by choosing one element from each of the given 383 * lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian 384 * product</a>" of the lists. For example: 385 * 386 * <pre>{@code 387 * Lists.cartesianProduct(ImmutableList.of( 388 * ImmutableList.of(1, 2), 389 * ImmutableList.of("A", "B", "C"))) 390 * }</pre> 391 * 392 * <p>returns a list containing six lists in the following order: 393 * 394 * <ul> 395 * <li>{@code ImmutableList.of(1, "A")} 396 * <li>{@code ImmutableList.of(1, "B")} 397 * <li>{@code ImmutableList.of(1, "C")} 398 * <li>{@code ImmutableList.of(2, "A")} 399 * <li>{@code ImmutableList.of(2, "B")} 400 * <li>{@code ImmutableList.of(2, "C")} 401 * </ul> 402 * 403 * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian 404 * products that you would get from nesting for loops: 405 * 406 * <pre>{@code 407 * for (B b0 : lists.get(0)) { 408 * for (B b1 : lists.get(1)) { 409 * ... 410 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); 411 * // operate on tuple 412 * } 413 * } 414 * }</pre> 415 * 416 * <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists 417 * at all are provided (an empty list), the resulting Cartesian product has one element, an empty 418 * list (counter-intuitive, but mathematically consistent). 419 * 420 * <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a 421 * list of size {@code m x n x p}, its actual memory consumption is much smaller. When the 422 * cartesian product is constructed, the input lists are merely copied. Only as the resulting list 423 * is iterated are the individual lists created, and these are not retained after iteration. 424 * 425 * @param lists the lists to choose elements from, in the order that the elements chosen from 426 * those lists should appear in the resulting lists 427 * @param <B> any common base class shared by all axes (often just {@link Object}) 428 * @return the Cartesian product, as an immutable list containing immutable lists 429 * @throws IllegalArgumentException if the size of the cartesian product would be greater than 430 * {@link Integer#MAX_VALUE} 431 * @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of 432 * a provided list is null 433 * @since 19.0 434 */ 435 public static <B> List<List<B>> cartesianProduct(List<? extends List<? extends B>> lists) { 436 return CartesianList.create(lists); 437 } 438 439 /** 440 * Returns every possible list that can be formed by choosing one element from each of the given 441 * lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian 442 * product</a>" of the lists. For example: 443 * 444 * <pre>{@code 445 * Lists.cartesianProduct(ImmutableList.of( 446 * ImmutableList.of(1, 2), 447 * ImmutableList.of("A", "B", "C"))) 448 * }</pre> 449 * 450 * <p>returns a list containing six lists in the following order: 451 * 452 * <ul> 453 * <li>{@code ImmutableList.of(1, "A")} 454 * <li>{@code ImmutableList.of(1, "B")} 455 * <li>{@code ImmutableList.of(1, "C")} 456 * <li>{@code ImmutableList.of(2, "A")} 457 * <li>{@code ImmutableList.of(2, "B")} 458 * <li>{@code ImmutableList.of(2, "C")} 459 * </ul> 460 * 461 * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian 462 * products that you would get from nesting for loops: 463 * 464 * <pre>{@code 465 * for (B b0 : lists.get(0)) { 466 * for (B b1 : lists.get(1)) { 467 * ... 468 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); 469 * // operate on tuple 470 * } 471 * } 472 * }</pre> 473 * 474 * <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists 475 * at all are provided (an empty list), the resulting Cartesian product has one element, an empty 476 * list (counter-intuitive, but mathematically consistent). 477 * 478 * <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a 479 * list of size {@code m x n x p}, its actual memory consumption is much smaller. When the 480 * cartesian product is constructed, the input lists are merely copied. Only as the resulting list 481 * is iterated are the individual lists created, and these are not retained after iteration. 482 * 483 * @param lists the lists to choose elements from, in the order that the elements chosen from 484 * those lists should appear in the resulting lists 485 * @param <B> any common base class shared by all axes (often just {@link Object}) 486 * @return the Cartesian product, as an immutable list containing immutable lists 487 * @throws IllegalArgumentException if the size of the cartesian product would be greater than 488 * {@link Integer#MAX_VALUE} 489 * @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of 490 * a provided list is null 491 * @since 19.0 492 */ 493 @SafeVarargs 494 public static <B> List<List<B>> cartesianProduct(List<? extends B>... lists) { 495 return cartesianProduct(Arrays.asList(lists)); 496 } 497 498 /** 499 * Returns a list that applies {@code function} to each element of {@code fromList}. The returned 500 * list is a transformed view of {@code fromList}; changes to {@code fromList} will be reflected 501 * in the returned list and vice versa. 502 * 503 * <p>Since functions are not reversible, the transform is one-way and new items cannot be stored 504 * in the returned list. The {@code add}, {@code addAll} and {@code set} methods are unsupported 505 * in the returned list. 506 * 507 * <p>The function is applied lazily, invoked when needed. This is necessary for the returned list 508 * to be a view, but it means that the function will be applied many times for bulk operations 509 * like {@link List#contains} and {@link List#hashCode}. For this to perform well, {@code 510 * function} should be fast. To avoid lazy evaluation when the returned list doesn't need to be a 511 * view, copy the returned list into a new list of your choosing. 512 * 513 * <p>If {@code fromList} implements {@link RandomAccess}, so will the returned list. The returned 514 * list is threadsafe if the supplied list and function are. 515 * 516 * <p>If only a {@code Collection} or {@code Iterable} input is available, use {@link 517 * Collections2#transform} or {@link Iterables#transform}. 518 * 519 * <p><b>Note:</b> serializing the returned list is implemented by serializing {@code fromList}, 520 * its contents, and {@code function} -- <i>not</i> by serializing the transformed values. This 521 * can lead to surprising behavior, so serializing the returned list is <b>not recommended</b>. 522 * Instead, copy the list using {@link ImmutableList#copyOf(Collection)} (for example), then 523 * serialize the copy. Other methods similar to this do not implement serialization at all for 524 * this reason. 525 * 526 * <p><b>Java 8 users:</b> many use cases for this method are better addressed by {@link 527 * java.util.stream.Stream#map}. This method is not being deprecated, but we gently encourage you 528 * to migrate to streams. 529 */ 530 public static <F extends @Nullable Object, T extends @Nullable Object> List<T> transform( 531 List<F> fromList, Function<? super F, ? extends T> function) { 532 return (fromList instanceof RandomAccess) 533 ? new TransformingRandomAccessList<>(fromList, function) 534 : new TransformingSequentialList<>(fromList, function); 535 } 536 537 /** 538 * Implementation of a sequential transforming list. 539 * 540 * @see Lists#transform 541 */ 542 private static class TransformingSequentialList< 543 F extends @Nullable Object, T extends @Nullable Object> 544 extends AbstractSequentialList<T> implements Serializable { 545 final List<F> fromList; 546 final Function<? super F, ? extends T> function; 547 548 TransformingSequentialList(List<F> fromList, Function<? super F, ? extends T> function) { 549 this.fromList = checkNotNull(fromList); 550 this.function = checkNotNull(function); 551 } 552 553 /** 554 * The default implementation inherited is based on iteration and removal of each element which 555 * can be overkill. That's why we forward this call directly to the backing list. 556 */ 557 @Override 558 protected void removeRange(int fromIndex, int toIndex) { 559 fromList.subList(fromIndex, toIndex).clear(); 560 } 561 562 @Override 563 public int size() { 564 return fromList.size(); 565 } 566 567 @Override 568 public ListIterator<T> listIterator(final int index) { 569 return new TransformedListIterator<F, T>(fromList.listIterator(index)) { 570 @Override 571 @ParametricNullness 572 T transform(@ParametricNullness F from) { 573 return function.apply(from); 574 } 575 }; 576 } 577 578 private static final long serialVersionUID = 0; 579 } 580 581 /** 582 * Implementation of a transforming random access list. We try to make as many of these methods 583 * pass-through to the source list as possible so that the performance characteristics of the 584 * source list and transformed list are similar. 585 * 586 * @see Lists#transform 587 */ 588 private static class TransformingRandomAccessList< 589 F extends @Nullable Object, T extends @Nullable Object> 590 extends AbstractList<T> implements RandomAccess, Serializable { 591 final List<F> fromList; 592 final Function<? super F, ? extends T> function; 593 594 TransformingRandomAccessList(List<F> fromList, Function<? super F, ? extends T> function) { 595 this.fromList = checkNotNull(fromList); 596 this.function = checkNotNull(function); 597 } 598 599 /** 600 * The default implementation inherited is based on iteration and removal of each element which 601 * can be overkill. That's why we forward this call directly to the backing list. 602 */ 603 @Override 604 protected void removeRange(int fromIndex, int toIndex) { 605 fromList.subList(fromIndex, toIndex).clear(); 606 } 607 608 @Override 609 @ParametricNullness 610 public T get(int index) { 611 return function.apply(fromList.get(index)); 612 } 613 614 @Override 615 public Iterator<T> iterator() { 616 return listIterator(); 617 } 618 619 @Override 620 public ListIterator<T> listIterator(int index) { 621 return new TransformedListIterator<F, T>(fromList.listIterator(index)) { 622 @Override 623 T transform(F from) { 624 return function.apply(from); 625 } 626 }; 627 } 628 629 // TODO: cpovirk - Why override `isEmpty` here but not in TransformingSequentialList? 630 631 @Override 632 public boolean isEmpty() { 633 return fromList.isEmpty(); 634 } 635 636 @Override 637 public T remove(int index) { 638 return function.apply(fromList.remove(index)); 639 } 640 641 @Override 642 public int size() { 643 return fromList.size(); 644 } 645 646 private static final long serialVersionUID = 0; 647 } 648 649 /** 650 * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, each of the same 651 * size (the final list may be smaller). For example, partitioning a list containing {@code [a, b, 652 * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list 653 * containing two inner lists of three and two elements, all in the original order. 654 * 655 * <p>The outer list is unmodifiable, but reflects the latest state of the source list. The inner 656 * lists are sublist views of the original list, produced on demand using {@link List#subList(int, 657 * int)}, and are subject to all the usual caveats about modification as explained in that API. 658 * 659 * @param list the list to return consecutive sublists of 660 * @param size the desired size of each sublist (the last may be smaller) 661 * @return a list of consecutive sublists 662 * @throws IllegalArgumentException if {@code partitionSize} is nonpositive 663 */ 664 public static <T extends @Nullable Object> List<List<T>> partition(List<T> list, int size) { 665 checkNotNull(list); 666 checkArgument(size > 0); 667 return (list instanceof RandomAccess) 668 ? new RandomAccessPartition<>(list, size) 669 : new Partition<>(list, size); 670 } 671 672 private static class Partition<T extends @Nullable Object> extends AbstractList<List<T>> { 673 final List<T> list; 674 final int size; 675 676 Partition(List<T> list, int size) { 677 this.list = list; 678 this.size = size; 679 } 680 681 @Override 682 public List<T> get(int index) { 683 checkElementIndex(index, size()); 684 int start = index * size; 685 int end = Math.min(start + size, list.size()); 686 return list.subList(start, end); 687 } 688 689 @Override 690 public int size() { 691 return IntMath.divide(list.size(), size, RoundingMode.CEILING); 692 } 693 694 @Override 695 public boolean isEmpty() { 696 return list.isEmpty(); 697 } 698 } 699 700 private static class RandomAccessPartition<T extends @Nullable Object> extends Partition<T> 701 implements RandomAccess { 702 RandomAccessPartition(List<T> list, int size) { 703 super(list, size); 704 } 705 } 706 707 /** 708 * Returns a view of the specified string as an immutable list of {@code Character} values. 709 * 710 * @since 7.0 711 */ 712 public static ImmutableList<Character> charactersOf(String string) { 713 return new StringAsImmutableList(checkNotNull(string)); 714 } 715 716 /** 717 * Returns a view of the specified {@code CharSequence} as a {@code List<Character>}, viewing 718 * {@code sequence} as a sequence of Unicode code units. The view does not support any 719 * modification operations, but reflects any changes to the underlying character sequence. 720 * 721 * @param sequence the character sequence to view as a {@code List} of characters 722 * @return an {@code List<Character>} view of the character sequence 723 * @since 7.0 724 */ 725 public static List<Character> charactersOf(CharSequence sequence) { 726 return new CharSequenceAsList(checkNotNull(sequence)); 727 } 728 729 @SuppressWarnings("serial") // serialized using ImmutableList serialization 730 private static final class StringAsImmutableList extends ImmutableList<Character> { 731 732 private final String string; 733 734 StringAsImmutableList(String string) { 735 this.string = string; 736 } 737 738 @Override 739 public int indexOf(@CheckForNull Object object) { 740 return (object instanceof Character) ? string.indexOf((Character) object) : -1; 741 } 742 743 @Override 744 public int lastIndexOf(@CheckForNull Object object) { 745 return (object instanceof Character) ? string.lastIndexOf((Character) object) : -1; 746 } 747 748 @Override 749 public ImmutableList<Character> subList(int fromIndex, int toIndex) { 750 checkPositionIndexes(fromIndex, toIndex, size()); // for GWT 751 return charactersOf(string.substring(fromIndex, toIndex)); 752 } 753 754 @Override 755 boolean isPartialView() { 756 return false; 757 } 758 759 @Override 760 public Character get(int index) { 761 checkElementIndex(index, size()); // for GWT 762 return string.charAt(index); 763 } 764 765 @Override 766 public int size() { 767 return string.length(); 768 } 769 770 // redeclare to help optimizers with b/310253115 771 @SuppressWarnings("RedundantOverride") 772 @Override 773 @J2ktIncompatible // serialization 774 @GwtIncompatible // serialization 775 Object writeReplace() { 776 return super.writeReplace(); 777 } 778 } 779 780 private static final class CharSequenceAsList extends AbstractList<Character> { 781 private final CharSequence sequence; 782 783 CharSequenceAsList(CharSequence sequence) { 784 this.sequence = sequence; 785 } 786 787 @Override 788 public Character get(int index) { 789 checkElementIndex(index, size()); // for GWT 790 return sequence.charAt(index); 791 } 792 793 @Override 794 public int size() { 795 return sequence.length(); 796 } 797 } 798 799 /** 800 * Returns a reversed view of the specified list. For example, {@code 801 * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3, 2, 1}. The returned 802 * list is backed by this list, so changes in the returned list are reflected in this list, and 803 * vice-versa. The returned list supports all of the optional list operations supported by this 804 * list. 805 * 806 * <p>The returned list is random-access if the specified list is random access. 807 * 808 * @since 7.0 809 */ 810 public static <T extends @Nullable Object> List<T> reverse(List<T> list) { 811 if (list instanceof ImmutableList) { 812 // Avoid nullness warnings. 813 List<?> reversed = ((ImmutableList<?>) list).reverse(); 814 @SuppressWarnings("unchecked") 815 List<T> result = (List<T>) reversed; 816 return result; 817 } else if (list instanceof ReverseList) { 818 return ((ReverseList<T>) list).getForwardList(); 819 } else if (list instanceof RandomAccess) { 820 return new RandomAccessReverseList<>(list); 821 } else { 822 return new ReverseList<>(list); 823 } 824 } 825 826 private static class ReverseList<T extends @Nullable Object> extends AbstractList<T> { 827 private final List<T> forwardList; 828 829 ReverseList(List<T> forwardList) { 830 this.forwardList = checkNotNull(forwardList); 831 } 832 833 List<T> getForwardList() { 834 return forwardList; 835 } 836 837 private int reverseIndex(int index) { 838 int size = size(); 839 checkElementIndex(index, size); 840 return (size - 1) - index; 841 } 842 843 private int reversePosition(int index) { 844 int size = size(); 845 checkPositionIndex(index, size); 846 return size - index; 847 } 848 849 @Override 850 public void add(int index, @ParametricNullness T element) { 851 forwardList.add(reversePosition(index), element); 852 } 853 854 @Override 855 public void clear() { 856 forwardList.clear(); 857 } 858 859 @Override 860 @ParametricNullness 861 public T remove(int index) { 862 return forwardList.remove(reverseIndex(index)); 863 } 864 865 @Override 866 protected void removeRange(int fromIndex, int toIndex) { 867 subList(fromIndex, toIndex).clear(); 868 } 869 870 @Override 871 @ParametricNullness 872 public T set(int index, @ParametricNullness T element) { 873 return forwardList.set(reverseIndex(index), element); 874 } 875 876 @Override 877 @ParametricNullness 878 public T get(int index) { 879 return forwardList.get(reverseIndex(index)); 880 } 881 882 @Override 883 public int size() { 884 return forwardList.size(); 885 } 886 887 @Override 888 public List<T> subList(int fromIndex, int toIndex) { 889 checkPositionIndexes(fromIndex, toIndex, size()); 890 return reverse(forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex))); 891 } 892 893 @Override 894 public Iterator<T> iterator() { 895 return listIterator(); 896 } 897 898 @Override 899 public ListIterator<T> listIterator(int index) { 900 int start = reversePosition(index); 901 final ListIterator<T> forwardIterator = forwardList.listIterator(start); 902 return new ListIterator<T>() { 903 904 boolean canRemoveOrSet; 905 906 @Override 907 public void add(@ParametricNullness T e) { 908 forwardIterator.add(e); 909 forwardIterator.previous(); 910 canRemoveOrSet = false; 911 } 912 913 @Override 914 public boolean hasNext() { 915 return forwardIterator.hasPrevious(); 916 } 917 918 @Override 919 public boolean hasPrevious() { 920 return forwardIterator.hasNext(); 921 } 922 923 @Override 924 @ParametricNullness 925 public T next() { 926 if (!hasNext()) { 927 throw new NoSuchElementException(); 928 } 929 canRemoveOrSet = true; 930 return forwardIterator.previous(); 931 } 932 933 @Override 934 public int nextIndex() { 935 return reversePosition(forwardIterator.nextIndex()); 936 } 937 938 @Override 939 @ParametricNullness 940 public T previous() { 941 if (!hasPrevious()) { 942 throw new NoSuchElementException(); 943 } 944 canRemoveOrSet = true; 945 return forwardIterator.next(); 946 } 947 948 @Override 949 public int previousIndex() { 950 return nextIndex() - 1; 951 } 952 953 @Override 954 public void remove() { 955 checkRemove(canRemoveOrSet); 956 forwardIterator.remove(); 957 canRemoveOrSet = false; 958 } 959 960 @Override 961 public void set(@ParametricNullness T e) { 962 checkState(canRemoveOrSet); 963 forwardIterator.set(e); 964 } 965 }; 966 } 967 } 968 969 private static class RandomAccessReverseList<T extends @Nullable Object> extends ReverseList<T> 970 implements RandomAccess { 971 RandomAccessReverseList(List<T> forwardList) { 972 super(forwardList); 973 } 974 } 975 976 /** An implementation of {@link List#hashCode()}. */ 977 static int hashCodeImpl(List<?> list) { 978 // TODO(lowasser): worth optimizing for RandomAccess? 979 int hashCode = 1; 980 for (Object o : list) { 981 hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); 982 983 hashCode = ~~hashCode; 984 // needed to deal with GWT integer overflow 985 } 986 return hashCode; 987 } 988 989 /** An implementation of {@link List#equals(Object)}. */ 990 static boolean equalsImpl(List<?> thisList, @CheckForNull Object other) { 991 if (other == checkNotNull(thisList)) { 992 return true; 993 } 994 if (!(other instanceof List)) { 995 return false; 996 } 997 List<?> otherList = (List<?>) other; 998 int size = thisList.size(); 999 if (size != otherList.size()) { 1000 return false; 1001 } 1002 if (thisList instanceof RandomAccess && otherList instanceof RandomAccess) { 1003 // avoid allocation and use the faster loop 1004 for (int i = 0; i < size; i++) { 1005 if (!Objects.equal(thisList.get(i), otherList.get(i))) { 1006 return false; 1007 } 1008 } 1009 return true; 1010 } else { 1011 return Iterators.elementsEqual(thisList.iterator(), otherList.iterator()); 1012 } 1013 } 1014 1015 /** An implementation of {@link List#addAll(int, Collection)}. */ 1016 static <E extends @Nullable Object> boolean addAllImpl( 1017 List<E> list, int index, Iterable<? extends E> elements) { 1018 boolean changed = false; 1019 ListIterator<E> listIterator = list.listIterator(index); 1020 for (E e : elements) { 1021 listIterator.add(e); 1022 changed = true; 1023 } 1024 return changed; 1025 } 1026 1027 /** An implementation of {@link List#indexOf(Object)}. */ 1028 static int indexOfImpl(List<?> list, @CheckForNull Object element) { 1029 if (list instanceof RandomAccess) { 1030 return indexOfRandomAccess(list, element); 1031 } else { 1032 ListIterator<?> listIterator = list.listIterator(); 1033 while (listIterator.hasNext()) { 1034 if (Objects.equal(element, listIterator.next())) { 1035 return listIterator.previousIndex(); 1036 } 1037 } 1038 return -1; 1039 } 1040 } 1041 1042 private static int indexOfRandomAccess(List<?> list, @CheckForNull Object element) { 1043 int size = list.size(); 1044 if (element == null) { 1045 for (int i = 0; i < size; i++) { 1046 if (list.get(i) == null) { 1047 return i; 1048 } 1049 } 1050 } else { 1051 for (int i = 0; i < size; i++) { 1052 if (element.equals(list.get(i))) { 1053 return i; 1054 } 1055 } 1056 } 1057 return -1; 1058 } 1059 1060 /** An implementation of {@link List#lastIndexOf(Object)}. */ 1061 static int lastIndexOfImpl(List<?> list, @CheckForNull Object element) { 1062 if (list instanceof RandomAccess) { 1063 return lastIndexOfRandomAccess(list, element); 1064 } else { 1065 ListIterator<?> listIterator = list.listIterator(list.size()); 1066 while (listIterator.hasPrevious()) { 1067 if (Objects.equal(element, listIterator.previous())) { 1068 return listIterator.nextIndex(); 1069 } 1070 } 1071 return -1; 1072 } 1073 } 1074 1075 private static int lastIndexOfRandomAccess(List<?> list, @CheckForNull Object element) { 1076 if (element == null) { 1077 for (int i = list.size() - 1; i >= 0; i--) { 1078 if (list.get(i) == null) { 1079 return i; 1080 } 1081 } 1082 } else { 1083 for (int i = list.size() - 1; i >= 0; i--) { 1084 if (element.equals(list.get(i))) { 1085 return i; 1086 } 1087 } 1088 } 1089 return -1; 1090 } 1091 1092 /** Returns an implementation of {@link List#listIterator(int)}. */ 1093 static <E extends @Nullable Object> ListIterator<E> listIteratorImpl(List<E> list, int index) { 1094 return new AbstractListWrapper<>(list).listIterator(index); 1095 } 1096 1097 /** An implementation of {@link List#subList(int, int)}. */ 1098 static <E extends @Nullable Object> List<E> subListImpl( 1099 final List<E> list, int fromIndex, int toIndex) { 1100 List<E> wrapper; 1101 if (list instanceof RandomAccess) { 1102 wrapper = 1103 new RandomAccessListWrapper<E>(list) { 1104 @Override 1105 public ListIterator<E> listIterator(int index) { 1106 return backingList.listIterator(index); 1107 } 1108 1109 @J2ktIncompatible private static final long serialVersionUID = 0; 1110 }; 1111 } else { 1112 wrapper = 1113 new AbstractListWrapper<E>(list) { 1114 @Override 1115 public ListIterator<E> listIterator(int index) { 1116 return backingList.listIterator(index); 1117 } 1118 1119 @J2ktIncompatible private static final long serialVersionUID = 0; 1120 }; 1121 } 1122 return wrapper.subList(fromIndex, toIndex); 1123 } 1124 1125 private static class AbstractListWrapper<E extends @Nullable Object> extends AbstractList<E> { 1126 final List<E> backingList; 1127 1128 AbstractListWrapper(List<E> backingList) { 1129 this.backingList = checkNotNull(backingList); 1130 } 1131 1132 @Override 1133 public void add(int index, @ParametricNullness E element) { 1134 backingList.add(index, element); 1135 } 1136 1137 @Override 1138 public boolean addAll(int index, Collection<? extends E> c) { 1139 return backingList.addAll(index, c); 1140 } 1141 1142 @Override 1143 @ParametricNullness 1144 public E get(int index) { 1145 return backingList.get(index); 1146 } 1147 1148 @Override 1149 @ParametricNullness 1150 public E remove(int index) { 1151 return backingList.remove(index); 1152 } 1153 1154 @Override 1155 @ParametricNullness 1156 public E set(int index, @ParametricNullness E element) { 1157 return backingList.set(index, element); 1158 } 1159 1160 @Override 1161 public boolean contains(@CheckForNull Object o) { 1162 return backingList.contains(o); 1163 } 1164 1165 @Override 1166 public int size() { 1167 return backingList.size(); 1168 } 1169 } 1170 1171 private static class RandomAccessListWrapper<E extends @Nullable Object> 1172 extends AbstractListWrapper<E> implements RandomAccess { 1173 RandomAccessListWrapper(List<E> backingList) { 1174 super(backingList); 1175 } 1176 } 1177 1178 /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ 1179 static <T extends @Nullable Object> List<T> cast(Iterable<T> iterable) { 1180 return (List<T>) iterable; 1181 } 1182}