Java 从数组创建 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/157944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create ArrayList from array
提问by Ron Tuffin
采纳答案by Tom
new ArrayList<>(Arrays.asList(array));
回答by Bill the Lizard
new ArrayList<T>(Arrays.asList(myArray));
Make sure that myArray
is the same type as T
. You'll get a compiler error if you try to create a List<Integer>
from an array of int
, for example.
确保它myArray
与T
. 例如,如果您尝试List<Integer>
从 的数组创建 ,则会出现编译器错误int
。
回答by Kip
You probably just need a List, not an ArrayList. In that case you can just do:
您可能只需要一个 List,而不是一个 ArrayList。在这种情况下,您可以这样做:
List<Element> arraylist = Arrays.asList(array);
回答by Alex Miller
Given:
鉴于:
Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
The simplest answer is to do:
最简单的答案是:
List<Element> list = Arrays.asList(array);
This will work fine. But some caveats:
这将正常工作。但一些警告:
- The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new
ArrayList
. Otherwise you'll get anUnsupportedOperationException
. - The list returned from
asList()
is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.
- 从 asList 返回的列表具有固定大小。因此,如果您希望能够在代码的返回列表中添加或删除元素,则需要将其包装在一个新的
ArrayList
. 否则你会得到一个UnsupportedOperationException
. - 返回的列表
asList()
由原始数组支持。如果修改原始数组,列表也将被修改。这可能令人惊讶。
回答by Tim Büthe
Since this question is pretty old, it surprises me that nobody suggested the simplest form yet:
由于这个问题已经很老了,让我感到惊讶的是没有人提出最简单的形式:
List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));
As of Java 5, Arrays.asList()
takes a varargs parameter and you don't have to construct the array explicitly.
从 Java 5 开始,Arrays.asList()
采用 varargs 参数,您不必显式构造数组。
回答by Peter Tseng
Another way (although essentially equivalent to the new ArrayList(Arrays.asList(array))
solution performance-wise:
另一种方式(虽然本质上等同于new ArrayList(Arrays.asList(array))
解决方案性能方面:
Collections.addAll(arraylist, array);
回答by haylem
(old thread, but just 2 cents as none mention Guava or other libs and some other details)
(旧线程,但只有 2 美分,因为没有人提到番石榴或其他库以及其他一些细节)
If You Can, Use Guava
如果可以,请使用番石榴
It's worth pointing out the Guava way, which greatly simplifies these shenanigans:
值得指出的是 Guava 方式,它极大地简化了这些恶作剧:
Usage
用法
For an Immutable List
对于不可变列表
Use the ImmutableList
class and its of()
and copyOf()
factory methods (elements can't be null):
使用ImmutableList
类及其of()
与copyOf()
工厂方法(内容不能为空):
List<String> il = ImmutableList.of("string", "elements"); // from varargs
List<String> il = ImmutableList.copyOf(aStringArray); // from array
For A Mutable List
对于可变列表
Use the Lists
class and its newArrayList()
factory methods:
使用Lists
类及其newArrayList()
工厂方法:
List<String> l1 = Lists.newArrayList(anotherListOrCollection); // from collection
List<String> l2 = Lists.newArrayList(aStringArray); // from array
List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs
Please also note the similar methods for other data structures in other classes, for instance in Sets
.
另请注意其他类中其他数据结构的类似方法,例如在Sets
.
Why Guava?
为什么是番石榴?
The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methodsallow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.
主要的吸引力可能是减少由于类型安全泛型造成的混乱,因为使用 Guava工厂方法允许在大多数时间推断类型。然而,自从 Java 7 与新的菱形运算符一起出现以来,这个论点就不那么成立了。
But it's not the only reason (and Java 7 isn't everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.
但这不是唯一的原因(Java 7 还不是无处不在):速记语法也非常方便,而且方法初始化器,如上所示,允许编写更具表现力的代码。您可以在一个 Guava 调用中完成需要 2 的当前 Java 集合。
If You Can't...
如果你不能...
For an Immutable List
对于不可变列表
Use the JDK's Arrays
class and its asList()
factory method, wrapped with a Collections.unmodifiableList()
:
使用 JDK 的Arrays
类及其asList()
工厂方法,用一个Collections.unmodifiableList()
:
List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));
List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2"));
Note that the returned type for asList()
is a List
using a concrete ArrayList
implementation, but it is NOTjava.util.ArrayList
. It's an inner type, which emulates an ArrayList
but actually directly references the passed array and makes it "write through" (modifications are reflected in the array).
请注意, for 的返回类型asList()
是List
using 一个具体ArrayList
实现,但它不是java.util.ArrayList
。它是一个内部类型,它模拟一个ArrayList
但实际上直接引用传递的数组并使其“直写”(修改反映在数组中)。
It forbids modifications through some of the List
API's methods by way of simply extending an AbstractList
(so, adding or removing elements is unsupported), however it allows calls to set()
to override elements. Thus this list isn't truly immutable and a call to asList()
should be wrapped with Collections.unmodifiableList()
.
它禁止通过List
简单地扩展AbstractList
(因此,不支持添加或删除元素)的方式通过某些API 的方法进行修改,但是它允许调用set()
来覆盖元素。因此这个列表并不是真正不可变的,调用asList()
应该用Collections.unmodifiableList()
.
See the next step if you need a mutable list.
如果您需要可变列表,请参阅下一步。
For a Mutable List
对于可变列表
Same as above, but wrapped with an actual java.util.ArrayList
:
与上面相同,但用实际的java.util.ArrayList
:
List<String> l1 = new ArrayList<String>(Arrays.asList(array)); // Java 1.5 to 1.6
List<String> l1b = new ArrayList<>(Arrays.asList(array)); // Java 1.7+
List<String> l2 = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6
List<String> l2b = new ArrayList<>(Arrays.asList("a", "b")); // Java 1.7+
For Educational Purposes: The Good ol' Manual Way
出于教育目的:良好的手动方式
// for Java 1.5+
static <T> List<T> arrayToList(final T[] array) {
final List<T> l = new ArrayList<T>(array.length);
for (final T s : array) {
l.add(s);
}
return (l);
}
// for Java < 1.5 (no generics, no compile-time type-safety, boo!)
static List arrayToList(final Object[] array) {
final List l = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
l.add(array[i]);
}
return (l);
}
回答by TwoThe
There is another option if your goal is to generate a fixed list at runtime, which is as simple as it is effective:
如果您的目标是在运行时生成固定列表,还有另一种选择,它既简单又有效:
static final ArrayList<Element> myList = generateMyList();
private static ArrayList<Element> generateMyList() {
final ArrayList<Element> result = new ArrayList<>();
result.add(new Element(1));
result.add(new Element(2));
result.add(new Element(3));
result.add(new Element(4));
return result;
}
The benefit of using this pattern is, that the list is for once generated very intuitively and therefore is very easy to modify even with large lists or complex initialization, while on the other hand always contains the same Elements on every actual run of the program (unless you change it at a later point of course).
使用这种模式的好处是,列表是一次性生成的,非常直观,因此即使使用大列表或复杂的初始化也很容易修改,而另一方面,在程序的每次实际运行中总是包含相同的元素(除非您稍后更改它)。
回答by Bohdan
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);
回答by Nicolas Zozol
If you use :
如果您使用:
new ArrayList<T>(Arrays.asList(myArray));
you maycreate and filltwo lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[]
array each time the capacity needs to be extended.
您可以创建和填充两个列表!两次填充一个大列表正是您不想做的,因为Object[]
每次需要扩展容量时,它都会创建另一个数组。
Fortunately the JDK implementation is fast and Arrays.asList(a[])
is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.
幸运的是,JDK 的实现速度很快,Arrays.asList(a[])
而且做得非常好。它创建了一种名为 Arrays.ArrayList 的 ArrayList,其中 Object[] 数据直接指向数组。
// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>
private final E[] a;
ArrayList(E[] array) {
a = array; // you point to the previous array
}
....
}
The dangerous side is that if you change the initial array, you change the List !Are you sure you want that ? Maybe yes, maybe not.
危险的一面是,如果更改初始数组,就会更改 List !你确定你想要那个?可能是可能不是。
If not, the most understandable way is to do this :
如果没有,最容易理解的方法是这样做:
ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
list.add(element);
}
Or as said @glglgl, you can create another independant ArrayList with :
或者如@glglgl 所说,您可以使用以下命令创建另一个独立的 ArrayList:
new ArrayList<T>(Arrays.asList(myArray));
I love to use Collections
, Arrays
, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.
我爱用Collections
,Arrays
或番石榴。但如果它不合适,或者你感觉不到,就写另一条不雅的行来代替。