提问人:Evgeny Kuznetsov 提问时间:6/28/2022 最后编辑:Mark RotteveelEvgeny Kuznetsov 更新时间:6/28/2022 访问量:122
在 Java 11 中将数组的内容作为元素添加到列表中 [duplicate]
Add a content of an array as an element to a list in Java 11 [duplicate]
问:
我有一个微不足道的问题,我正在思考但没有成功。
假设我们有一个这样的代码片段:
int x[] = new int[]{3,4};
List<int[]> testList = new ArrayList<>();
testList.add(x.clone());
//testList.add(Arrays.copyOf(x,x.length)); -neither this works
System.out.println(testList);
代码打印:[[I@6442b0a6]
据我了解,在上面的代码中,我传递了一个指向 .但是我想传递的内容,以便包含副本作为元素?x
testList
x
testList
x
更重要的是,我想在没有显式迭代的情况下做到这一点。x
答:
3赞
Joop Eggen
6/28/2022
#1
最接近您的代码:
Integer[] x = {3, 4};
List<Integer> testList = new ArrayList<>();
Collections.addAll(testList, x); // Size 2.
System.out.println(testList);
由于 List 包含 Object 类,因此必须将 s 框为 Integer。Integer
int
int[] x = {3, 4};
List<Integer> testList = IntStream.of(x).boxed().collect(Collectors.toList());
澄清后
int[] x = {3, 4};
List<int[]> testList = new ArrayList<>();
testList.add(x);
for (int[] y: testList) {
System.out.println(Arrays.toString(y));
}
评论
0赞
Evgeny Kuznetsov
6/28/2022
对不起,我想在最后收到一个数组列表
0赞
Evgeny Kuznetsov
6/28/2022
我已经接受了这个(唯一存在的)答案,但我也给其他人无形的功劳!
评论
int[] x = { 3, 4}
[]
<>
ArrayList
List<Integer> testList = new ArrayList<>();
testList.add(x);
List<int[]> testList = new ArrayList<>();
x.clone()
x
List<Integer>
List<int[]>
[[I@6442b0a6]
[..]
[I@6442b0a6
[I
int[]
6442b0a6
x
x
[I@6442b0a6
Arrays#toString(...)
List
String
List#toString()
toString
System.out.println
testList.forEach(arr -> System.out.println(Arrays.toString(arr)));