lenth()、length、size()

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长度的对象就等待被回收。所以当创建固定长度的对象时,数组效率更高。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值