在 Java 中将数组分配给 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3746639/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:14:50  来源:igfitidea点击:

Assigning an array to an ArrayList in Java

javaarraylist

提问by Steffan Harris

I was wondering if it is possible to assign an array to an ArrayList in Java.

我想知道是否可以将数组分配给 Java 中的 ArrayList。

回答by NullUserException

You can use Arrays.asList():

您可以使用Arrays.asList()

Type[] anArray = ...
ArrayList<Type> aList = new ArrayList<Type>(Arrays.asList(anArray));

or alternatively, Collections.addAll():

或者,Collections.addAll()

ArrayList<Type> aList = new ArrayList<Type>();
Collections.addAll(theList, anArray); 

Note that you aren't technically assigning an array to a List (well, you can't do that), but I think this is the end result you are looking for.

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

回答by Richard Cook

The Arraysclass contains an asListmethod which you can use as follows:

Arrays类包含asList您可以按如下方式使用方法:

String[] words = ...;
List<String> wordList = Arrays.asList(words);

回答by Andy

If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:

如果您正在导入或您的代码中有一个数组(字符串类型)并且您必须将其转换为数组列表(课外字符串),那么使用集合会更好。像这样:

String array1[] = getIntent().getExtras().getStringArray("key1"); or
String array1[] = ...
then

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

回答by JamesBong

This is working

这是工作

    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]