[[我不能被转换为 [I Exception
[[I cannot be cast to [I Exception
谁能解释这个异常以及这段代码中实际发生的事情:
public class Dims {
public static void main(String[] args) {
int[][] a = {{1, 2,}, {3, 4}};
int[] b = (int[]) a[1];
Object o1 = a;
int[][] a2 = (int[][]) o1;
int[] b2 = (int[]) o1; //Exception in thread "main" java.lang.ClassCastException: [[I cannot be cast to [I
System.out.println(b[1]);
}
}
int[]
与 int[][]
不兼容,因此您无法将一个转换为另一个,但您正在尝试这样做。 o1
的 运行 时间类型是 int[][]
,而您正试图将其转换为 int[]
。
好的,为什么这些类型称为 [[I
和 [I
?您可以尝试 运行 int[].class.toString()
和 int[][].class.toString
来理解这一点。 int[].class
将用代码 [
(表示数组)I
(表示整数)表示,int[][].class
将表示为 [[
(这意味着 I
(整数)的数组)。
异常是因为您将 2d 数组转换为 1d
[[I
表示二维数组class
[[
表示二维数组
[I
表示一维数组class
[
表示一维数组
I
是整数
您不能将二维数组转换为一维数组。在这里你得到相同的 [[I cannot be cast to [I
因为 o1 is internally pointing to 2_D integer array and b2 is 1-D array
.
代替那一行你可以这样做:
int[] b2 = ((int[][])o1)[0];
此处[[I
表示编译器将基本类型包装为Integer class并创建了Integer类型的二维数组对象。 [I
表示整数类型的一维数组。
谁能解释这个异常以及这段代码中实际发生的事情:
public class Dims {
public static void main(String[] args) {
int[][] a = {{1, 2,}, {3, 4}};
int[] b = (int[]) a[1];
Object o1 = a;
int[][] a2 = (int[][]) o1;
int[] b2 = (int[]) o1; //Exception in thread "main" java.lang.ClassCastException: [[I cannot be cast to [I
System.out.println(b[1]);
}
}
int[]
与 int[][]
不兼容,因此您无法将一个转换为另一个,但您正在尝试这样做。 o1
的 运行 时间类型是 int[][]
,而您正试图将其转换为 int[]
。
好的,为什么这些类型称为 [[I
和 [I
?您可以尝试 运行 int[].class.toString()
和 int[][].class.toString
来理解这一点。 int[].class
将用代码 [
(表示数组)I
(表示整数)表示,int[][].class
将表示为 [[
(这意味着 I
(整数)的数组)。
异常是因为您将 2d 数组转换为 1d
[[I
表示二维数组class
[[
表示二维数组
[I
表示一维数组class
[
表示一维数组
I
是整数
您不能将二维数组转换为一维数组。在这里你得到相同的 [[I cannot be cast to [I
因为 o1 is internally pointing to 2_D integer array and b2 is 1-D array
.
代替那一行你可以这样做:
int[] b2 = ((int[][])o1)[0];
此处[[I
表示编译器将基本类型包装为Integer class并创建了Integer类型的二维数组对象。 [I
表示整数类型的一维数组。