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