【问题标题】:Converting Array of int to ArrayList and vice versa [duplicate]将int数组转换为ArrayList,反之亦然[重复]
【发布时间】:2023-03-17 08:02:01
【问题描述】:

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

}

【问题讨论】:

  • Java 8+,使用IntStream

标签: java arrays arraylist


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2020-10-24
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多