View Javadoc
1   package com.github.davidmoten.guavamini;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   import java.util.Collections;
6   import java.util.Iterator;
7   
8   import com.github.davidmoten.guavamini.annotations.VisibleForTesting;
9   
10  public final class Lists {
11  
12      private Lists() {
13          // cannot instantiate
14      }
15  
16      public static <E> ArrayList<E> newArrayList(@SuppressWarnings("unchecked") E... elements) {
17          Preconditions.checkNotNull(elements);
18          // Avoid integer overflow when a large array is passed in
19          int capacity = computeArrayListCapacity(elements.length);
20          ArrayList<E> list = new ArrayList<E>(capacity);
21          Collections.addAll(list, elements);
22          return list;
23      }
24  
25      @VisibleForTesting
26      static int computeArrayListCapacity(int arraySize) {
27          Preconditions.checkArgument(arraySize >= 0, "arraySize must be non-negative");
28  
29          // TODO(kevinb): Figure out the right behavior, and document it
30          return saturatedCast(5L + arraySize + (arraySize / 10));
31      }
32  
33      /**
34       * Returns the {@code int} nearest in value to {@code value}.
35       *
36       * @param value
37       *            any {@code long} value
38       * @return the same value cast to {@code int} if it is in the range of the
39       *         {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
40       *         or {@link Integer#MIN_VALUE} if it is too small
41       */
42      @VisibleForTesting
43      static int saturatedCast(long value) {
44          if (value > Integer.MAX_VALUE) {
45              return Integer.MAX_VALUE;
46          }
47          if (value < Integer.MIN_VALUE) {
48              return Integer.MIN_VALUE;
49          }
50          return (int) value;
51      }
52  
53      public static <E> ArrayList<E> newArrayList() {
54          return new ArrayList<E>();
55      }
56  
57      public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
58          Preconditions.checkNotNull(elements); // for GWT
59          // Let ArrayList's sizing logic work, if possible
60          return (elements instanceof Collection) ? new ArrayList<E>(Collections2.cast(elements))
61                  : newArrayList(elements.iterator());
62      }
63  
64      public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
65          ArrayList<E> list = newArrayList();
66          Iterators.addAll(list, elements);
67          return list;
68      }
69  }