简体   繁体   English

在 Java 中将数组分配给 ArrayList

[英]Assigning an array to an ArrayList in Java

是否可以将array分配给 Java 中的ArrayList

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(好吧,您不能这样做),但我认为这是您正在寻找的最终结果。

The Arrays class contains an asList method which you can use as follows: Arrays类包含一个asList方法,您可以按如下方式使用它:

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

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);

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM