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