zoukankan      html  css  js  c++  java
  • 奇怪的组数length属性

    Java中的数组其实也是一个对象,但是确实是一个特殊的对象,实在是太特殊了,继承自Object, 多出一个属性length,改写了clone方法。
     
    我debug了数组对象的运行时的Class对象,只有一个name属性,用[L开头,其他属性全是null。
    调用getDeclaredFields,getDeclaredMethods都没有数据。这就奇怪了,明明可以用的length属性在哪的呢
     
    stackoverflow上有简单的解释:

    Arrays are special objects in java, they have a simple attribute named length which is final.

    There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

    10.7. Array Members

    The members of an array type are all of the following:

    • The public final field length, which contains the number of components of the array. lengthmay be positive or zero.
    • The public method clone, which overrides the method of the same name in class Objectand throws no checked exceptions. The return type of the clone method of an array type T[]is T[].

      A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

    • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
     
    看了上面英文我的理解是数组是java底层的类,可能是用c语言写的,所以在java语言Class类定义上,都找不到length属性和clone方法的声明。这里强调一点数组的clone是浅复制,也就是多维数组的时候,只会克隆第一维,后面维的都是指向相同地址的指针。
     

    It's "special" basically, with its own bytecode instruction: arraylength. So this method:

    public static void main(String[] args){
      int x = args.length;
    }

    is compiled into bytecode like this:
    public static void main(java.lang.String[]);

    Code:
      0: aload_0 1: arraylength 2: istore_1 3: return

    通过javap更好的说明了数组的length属性,其实是一个单独的二进制指令:arraylength

  • 相关阅读:
    css基础属性
    选择器的类型
    css的三种表现形式
    表单和表格
    如何比较两个xml 的异同
    xslt 简单的语法
    xslt 和一个demo
    event based xml parser (SAX) demo
    SAX vs. DOM (Event vs. Tree)
    xmlns 实例分析
  • 原文地址:https://www.cnblogs.com/onlywujun/p/3560017.html
Copyright © 2011-2022 走看看