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
14 }
15
16 public static <E> ArrayList<E> newArrayList(@SuppressWarnings("unchecked") E... elements) {
17 Preconditions.checkNotNull(elements);
18
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
30 return saturatedCast(5L + arraySize + (arraySize / 10));
31 }
32
33
34
35
36
37
38
39
40
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);
59
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 }