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