avatar
How is the future of IC# Engineering - 工程
Q*r
1
int [][] a ={{1,2}, {2,3}};
Object o = a;
int b = (int []) o;
编译能通过,但是有ClassCastException在第三句
不能理解,为什么能够编译通过?
如果是
int [][] a ={{1,2}, {2,3}};
Object o = a;
int b = (int []) a;
编译就不能通过了,在第三句。这个很容易理解。
avatar
y*h
2
How is the future of IC? Much better than wireless networking? Have to make
a choice between IC and wireless networking. Thanks.
avatar
F*n
3

~~~~~~~~~~~~~~~~~~~~~~~~~~
Are you sure it's not int[] b = (int[])o;

【在 Q****r 的大作中提到】
: int [][] a ={{1,2}, {2,3}};
: Object o = a;
: int b = (int []) o;
: 编译能通过,但是有ClassCastException在第三句
: 不能理解,为什么能够编译通过?
: 如果是
: int [][] a ={{1,2}, {2,3}};
: Object o = a;
: int b = (int []) a;
: 编译就不能通过了,在第三句。这个很容易理解。

avatar
Q*r
4
谢谢,提醒,已经改了

【在 F****n 的大作中提到】
:
: ~~~~~~~~~~~~~~~~~~~~~~~~~~
: Are you sure it's not int[] b = (int[])o;

avatar
F*n
5
Then it's obvious, an object can be a primitive array,
but an "array of primitive array" (which is actually an object array) can
never be a primitive array.

【在 Q****r 的大作中提到】
: 谢谢,提醒,已经改了
avatar
e*3
6
因为OOP的三要素之一的polymorphism,java 编译器只会在乎一个变量被申明成什么
type,而不考虑等号右边的赋值语句,那是jvm runtime运行时候才看得东西,所以java
编译器不能判定o在runtime是不是int[] type,因为o被declare是object,所以可能是
任何type,但是会给出class casting warning message.而运行的时候,o实际上是int[
][] type,不能cast到int[],所以jvm会throw一个RuntimeException/
ClassCastException,注意看naming, runtime exception,已经说明了它的含义。
第二个编译不能过,是因为a被declare了为int[][] type,所以java编译器可以确定a一
定是int[][](int[][]没有子类),不能被cast成int[],所以会给出编译错误。

【在 Q****r 的大作中提到】
: int [][] a ={{1,2}, {2,3}};
: Object o = a;
: int b = (int []) o;
: 编译能通过,但是有ClassCastException在第三句
: 不能理解,为什么能够编译通过?
: 如果是
: int [][] a ={{1,2}, {2,3}};
: Object o = a;
: int b = (int []) a;
: 编译就不能通过了,在第三句。这个很容易理解。

avatar
Q*r
7
谢谢阿,很详细

java
int[

【在 e********3 的大作中提到】
: 因为OOP的三要素之一的polymorphism,java 编译器只会在乎一个变量被申明成什么
: type,而不考虑等号右边的赋值语句,那是jvm runtime运行时候才看得东西,所以java
: 编译器不能判定o在runtime是不是int[] type,因为o被declare是object,所以可能是
: 任何type,但是会给出class casting warning message.而运行的时候,o实际上是int[
: ][] type,不能cast到int[],所以jvm会throw一个RuntimeException/
: ClassCastException,注意看naming, runtime exception,已经说明了它的含义。
: 第二个编译不能过,是因为a被declare了为int[][] type,所以java编译器可以确定a一
: 定是int[][](int[][]没有子类),不能被cast成int[],所以会给出编译错误。

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。