This question already has answers here:
Convert an array of primitive longs into a List of Longs
                            
                                (17个答案)
                            
                    
                3年前关闭。
        

    

我有一个数组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) + " ");
}


}

最佳答案

接受for循环的必然性:

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


...或在Java 8中使用流,尽管坦白地说,在这种情况下,它们比它们值得的更多痛苦:

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


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

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

07-22 03:48