字符串中的字符数量可以用String.length()得到,查看jdk源代码可以看到
/**
* Returns the length of this string.
* The length is equal to the number of <a href="Character.html#unicode">Unicode
* code units</a> in the string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
public int length() {
return count;
}
而返回数据组中元素的个数,可以用Array.length (注意不是方法)。
-->问题在这里:这个length是什么,某个类的field吗?方法吗?(显然不是)。
其实,field也不是。一个数组的方法,主要继承于object类,clone方法来源于数组元素类,而lengh这个属性是不存在的。对一个array进行取length的操作,会转化为JVM的一个特殊操作,而不是对一般field的读取。
这一点用javap查看编译后class文件的字节码就可以看到。
/**
* Returns the length of this string.
* The length is equal to the number of <a href="Character.html#unicode">Unicode
* code units</a> in the string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
public int length() {
return count;
}
而返回数据组中元素的个数,可以用Array.length (注意不是方法)。
-->问题在这里:这个length是什么,某个类的field吗?方法吗?(显然不是)。
其实,field也不是。一个数组的方法,主要继承于object类,clone方法来源于数组元素类,而lengh这个属性是不存在的。对一个array进行取length的操作,会转化为JVM的一个特殊操作,而不是对一般field的读取。
这一点用javap查看编译后class文件的字节码就可以看到。