Java 原始数组的 toArray() 转换
Java toArray() conversion for primitive arrays
我无法理解为什么转换为原始数组对于一维数组失败但适用于二维情况。
public static void main( String[] args ) throws IOException {
List<Integer> oneD = List.of(1,2,3);
int[] one = oneD.toArray(int[]::new); // error
List<int[]> twoD = List.of(
new int[]{1,2},
new int[]{3,4}
);
int[][] two = twoD.toArray(int[][]::new); // works
}
我尝试浏览文档,但无济于事。我可以看到的一件事是,在第一种情况下,因为我们试图从 Integer
转换为 int
,可能是导致错误的原因,并且第二种情况工作正常,因为 [=14] =] 将是一个对象类型。
用示例解释 toArray
的工作原理,尤其是对于基元,这将非常有帮助。
是的,Integer
与 int
完全不同。 int[]
不是 Object[]
.
还有,二维数组?你错了;那些不存在。 int[][]
不是二维整数数组。它是 int 数组的一维数组。有一些简单的语法糖可以让你写 int[][] x = new int[5][10];
,这是糖:
int[][] x = new int[5][];
for (int i = 0; i < x.length; i++) x[i] = new int[10];
这很好也很方便,但在引擎盖下它不是二维数组;这些不存在。 x.getClass()
的 'component type' 是 int[].class - and then array can be 'disjointed' (you can have row 0 contain 5 cells, and row 1 contain 10 cells, i.e. you could write
x[1] = new int[20];` 这很好用。
这就是 twoD
示例有效的原因。
要将 List<Integer>
转换为 int[]
,请编写 for 循环。
List<Integer> list = ...;
int[] arr = new int[list.size()];
for (int i = 0; i < list.size(); i++) arr[i] = list.get(i);
toArray
无法生成原始数组,因为 List
s 不能包含原始元素。
您可以使用IntStream
来实现无显式循环的转换:
int[] one = oneD.stream ().mapToInt (Integer::intValue).toArray ();
我无法理解为什么转换为原始数组对于一维数组失败但适用于二维情况。
public static void main( String[] args ) throws IOException {
List<Integer> oneD = List.of(1,2,3);
int[] one = oneD.toArray(int[]::new); // error
List<int[]> twoD = List.of(
new int[]{1,2},
new int[]{3,4}
);
int[][] two = twoD.toArray(int[][]::new); // works
}
我尝试浏览文档,但无济于事。我可以看到的一件事是,在第一种情况下,因为我们试图从 Integer
转换为 int
,可能是导致错误的原因,并且第二种情况工作正常,因为 [=14] =] 将是一个对象类型。
用示例解释 toArray
的工作原理,尤其是对于基元,这将非常有帮助。
是的,Integer
与 int
完全不同。 int[]
不是 Object[]
.
还有,二维数组?你错了;那些不存在。 int[][]
不是二维整数数组。它是 int 数组的一维数组。有一些简单的语法糖可以让你写 int[][] x = new int[5][10];
,这是糖:
int[][] x = new int[5][];
for (int i = 0; i < x.length; i++) x[i] = new int[10];
这很好也很方便,但在引擎盖下它不是二维数组;这些不存在。 x.getClass()
的 'component type' 是 int[].class - and then array can be 'disjointed' (you can have row 0 contain 5 cells, and row 1 contain 10 cells, i.e. you could write
x[1] = new int[20];` 这很好用。
这就是 twoD
示例有效的原因。
要将 List<Integer>
转换为 int[]
,请编写 for 循环。
List<Integer> list = ...;
int[] arr = new int[list.size()];
for (int i = 0; i < list.size(); i++) arr[i] = list.get(i);
toArray
无法生成原始数组,因为 List
s 不能包含原始元素。
您可以使用IntStream
来实现无显式循环的转换:
int[] one = oneD.stream ().mapToInt (Integer::intValue).toArray ();