在Java中将一个数组赋值给ArrayList

24

在Java中,是否可以将一个array赋值给一个ArrayList

4个回答

42
你可以使用 Arrays.asList() 方法:
Type[] anArray = ...
ArrayList<Type> aList = new ArrayList<Type>(Arrays.asList(anArray));

或者,也可以使用Collections.addAll()方法:
ArrayList<Type> aList = new ArrayList<Type>();
Collections.addAll(theList, anArray); 

请注意,您并没有在将数组分配给List(好吧,您不能这样做),但我认为这是您正在寻找的最终结果。

这个答案比我的好! - Richard Cook
Collections.addAll(theList, anArray); 对我很有帮助。非常感谢! :) - Jagadish Nallappa

6
Arrays类包含一个asList方法,您可以按照以下方式使用它:
String[] words = ...;
List<String> wordList = Arrays.asList(words);

2
这将返回一个由某些私有类型封装的固定大小的字符串列表,该类型实现了List<String>接口。如果您需要可变的java.util.ArrayList实例,则@NullUserException的答案是最好的。 - Richard Cook
Richard,我想知道为什么上面的列表变成了固定大小?我不能在下一行中向同一列表添加另一个元素吗,比如wordList.add(anotherStringElement); - peakit
这是asList方法的定义行为。正如@NullUserException所指出的那样,您应该转换为ArrayList [ArrayList <Type> aList = new ArrayList <Type>(Arrays.asList(words)],以便获得一个可以添加更多项的ArrayList。 - Richard Cook

2
如果您正在导入或者您的代码中有一个字符串数组,需要将其转换成ArrayList(当然是字符串类型的),那么使用collections库会更好。就像这样:
String array1[] = getIntent().getExtras().getStringArray("key1"); or
String array1[] = ...
then

List<String> allEds = new ArrayList<String>();
Collections.addAll(allEds, array1);

1

这是有效的

    int[] ar = {10, 20, 20, 10, 10, 30, 50, 10, 20};

    ArrayList<Integer> list = new ArrayList<>();

    for(int i:ar){
        list.add(new Integer(i));

    }
    System.out.println(list.toString());

    // prints : [10, 20, 20, 10, 10, 30, 50, 10, 20]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接