将一个int数组附加到的ArrayList中

时间:2021-02-11 21:15:51

Is there a shortcut to add (in fact append ) an array of int to an ArrayList? for the following example

是否有一个快捷方式可以将一个int数组添加(实际上是附加)到ArrayList中?对于以下示例

ArrayList<Integer> list=new ArrayList<Integer>();  
    int[] ints={2,4,5,67,8};  

Or do I have to add the elements of ints one by one to list?

或者我必须逐个添加整数元素列表?

1 个解决方案

#1


5  

Using Arrays.asList(ints) as suggested by others won't work (it'll give a list of int[] rather than a list of Integer).

使用其他人建议的Arrays.asList(ints)将不起作用(它将给出int []列表而不是Integer列表)。

The only way I can think of is to add the elements one by one:

我能想到的唯一方法是逐个添加元素:

    for (int val : ints) {
        list.add(val);
    }

If you can turn your int[] into Integer[], then you can use addAll():

如果你可以将int []转换为Integer [],那么你可以使用addAll():

    list.addAll(Arrays.asList(ints));

#1


5  

Using Arrays.asList(ints) as suggested by others won't work (it'll give a list of int[] rather than a list of Integer).

使用其他人建议的Arrays.asList(ints)将不起作用(它将给出int []列表而不是Integer列表)。

The only way I can think of is to add the elements one by one:

我能想到的唯一方法是逐个添加元素:

    for (int val : ints) {
        list.add(val);
    }

If you can turn your int[] into Integer[], then you can use addAll():

如果你可以将int []转换为Integer [],那么你可以使用addAll():

    list.addAll(Arrays.asList(ints));