黑马程序员技术交流社区

标题: 关于数组字节码 [打印本页]

作者: zhaihao    时间: 2014-9-20 22:59
标题: 关于数组字节码
public class Test {
        public static void main(String[] args) {
                int[] a1=new int[3];
                int[] a2=new int[4];
                int[][] a3=new int[2][3];
                String[] a4=new String[3];
                System.out.println(a1.getClass()== a2.getClass());//true
                System.out.println(a1.getClass()== a4.getClass());//false
                System.out.println(a1.getClass()== a3.getClass());//false

                System.out.println(a1.getClass().getName());//[I

        }

}
为什么编译时会报错????


QQ图片20140920202932.jpg (113.61 KB, 下载次数: 79)

上图

上图

作者: 荣英洁    时间: 2014-9-20 22:59
本帖最后由 荣英洁 于 2014-9-21 00:41 编辑

通过 Eclipse 的错误提示得到如下信息:
Multiple markers at this line
- Incompatible operand types Class<capture#7-of ? extends int[]> and Class<capture#8-of ? extends
  int[][]>
大致的意思是:不兼容的操作数类型类  ,这里所指的不相容类型就是 int[] 和 int[][] ;
但是通过以下这种方式就能通过编译:  
    int[] a1=new int[3];
          int[] a2=new int[4];
          int[][] a3=new int[2][3];
          String[] a4=new String[3];
          Class clz1 = a1.getClass();
          Class clz2 = a2.getClass();
          Class clz3 = a3.getClass();
          Class clz4 = a4.getClass();
          System.out.println(a1.getClass()== a2.getClass());//true
          System.out.println(clz1== clz4);//false
          System.out.println(clz1== clz3);//false
          System.out.println(a1.getClass().getName());//[I
因为以上的clz 都是 Class 类型,也就是类类型一致,只是描述的字节码不一样 ,因而编译通过,而a3.getClass() == a4.getClass(),编译器明确知道了他们的类型,检查到不一致,所以通不过,看下面的例子 同样不能通过编译
          Integer i = new Integer(10);
          Character c = new Character('a');
          System.out.println(i.getClass()==c.getClass());
也是同样的道理,编译器检查到两者的类类型不一致。



作者: zhangshoutuo    时间: 2014-9-21 00:08
所有类型相同和维数相同的数组它的的类字节码都是一样的

a1的类字节码 与a3、a4的类字节码永远都不会一样

jdk1.5以后,编译器认为这2个类型是不一样的。

根本没有比较的需要。对于总是不成立的比较,其实是没有意义的

所以编译器会报错!  




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2