gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:40:35 25 4
gpt4 key购买 nike

我有一个数组 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 中使用流,但坦率地说,在这种情况下,它们带来的痛苦超过了它们的值(value):

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

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

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

关于java - 将 int 数组转换为 ArrayList,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com