简体   繁体   English

为什么这段代码不会引发classcast异常?

[英]Why this code does not throw classcast exception?

Object o=new int[]{1,2,3}; 
int[] array=(int[]) o; 
for(int a:array){
  //print the values
}

-Why dont i get a classcast exception here while iterating through the array given that array extends Object class? -为什么在给定数组扩展Object类的情况下遍历数组时为什么没有在这里得到类广播异常?

Because in java even arrays are Objects . 因为在Java中, 甚至数组都是Objects . If you print array instanceof Object , it returns true. 如果打印array instanceof Object ,则返回true。

Next, you are creating an array and using an Objects reference. 接下来,您将创建一个数组并使用对象引用。 Since the final instance is an array , you will not get any exception. 由于最终实例是一个数组 ,因此不会有任何异常。

Object is the Super Class for all the Classes in Java. Object是Java中所有类的超类。 Every Class Extends Object Implcitly. 每个类都隐式扩展对象。 So, instances of any class can be cast into Object type. 因此,任何类的实例都可以转换为Object类型。

Because o itself is array of int[] -array type. 因为o本身 int[] -array类型的数组。 If it would be, for example, o = new long[] {...} - in this case, yes, it will throw an exception. 例如,如果为o = new long[] {...} -在这种情况下,是的,它将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM