length()
众所周知,获取字符串的长度时是使用length()方法,而获取数组的长度时是使用数组名.length,为何不统一,为什么字符串没有length属性,数组没有length()方法。
首先,查看源码我们知道,字符串数据类型是使用final修饰的,而且是用byte[]数组存储的:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence,
Constable, ConstantDesc {
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents
* of the array. No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
@Stable
private final byte[] value;
length()方法的源码为:
/**
* 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 value.length >> coder();
}
也就是说,因为字符串是用byte[]存储的数据,所以获取字符串的长度时使用一个方法返回byte[]的长度就可以,即:
value.length
length
再看数组,常说获取数组长度时是获取数组的length属性,但是有趣的事情发生了,没有一个类中定义了length这个属性,包括Object类,同时创建一个数组后,使用getDeclaredFields()结果为0,即没有属性。
其实,数组被Java特殊处理过
获取数组的长度如:array.length;
会出现一条指令:arraylength,Java为数组定义了一条获取长度的指令,所以length既不是方法也不是属性。
size()
最后是size()
size()用于集合获取长度。
注:创建一个集合时,默认为10个长度,如需继续添加,即添加第11个元素时,会按照1.5倍的长度扩容,变为了15个长度,原来10长度的对象就等待被回收。所以当创建固定长度的对象时,数组效率更高。