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