将int数组转换为ArrayList,反之亦然

时间:2017-03-13 01:17:08

标签: java arrays arraylist

我有一个数组int [] a = {1,2,3}我想将它转换为ArrayList,反之亦然。这些是我的尝试,但它们不起作用。请有人指出我正确的方向。

以下是我在下面的尝试

public class ALToArray_ArrayToAL {
public static void main(String[] args) {
    ALToArray_ArrayToAL obj = new ALToArray_ArrayToAL();

    obj.populateALUsingArray();
}

public void populateArrayUsingAL()
{
    ArrayList<Integer> al = new ArrayList<>();
    al.add(1);al.add(2);al.add(3);al.add(4);

    /* Don't want to do the following, is there a better way */
    int[] a = new int[al.size()];
    for(int i = 0;i<al.size();i++)
        a[i] = al.get(i);

    /* This does not work either */
    int[] b = al.toArray(new int[al.size()]);
}

public void populateALUsingArray()
{
    /* This does not work, and results in a compile time error */
    int[] a = {1,2,3};
    ArrayList<Integer> al = new ArrayList<>(Arrays.asList(a));


    /* Does not work because I want an array of ints, not int[] */
    int[] b = {4,5,6};
    List list = new ArrayList(Arrays.asList(b));
    for(int i = 0;i<list.size();i++)
        System.out.print(list.get(i) + " ");
}

}

1 个答案:

答案 0 :(得分:1)

接受for循环的必然性:

for (int i : array) {
  list.add(i);
}

...或者在Java 8中使用流,但坦率地说,他们更难以为这个案例带来痛苦:

Arrays.stream(array).boxed().collect(Collectors.toList())

...或使用像Guava这样的第三方库并编写

List<Integer> list = Ints.asList(array);