Android和Java中String.substring的不同实现

今天有幸去搜狗霸笔,有一题很有意思

String str1 = "test for sougou";
String str2 = str1.substring(5);

考点是str2是否生成新的字符数组来保存"for sougou"


当时我认为String内部是封装了一个char[],无法像cpp一样首地址加上一个数字来做到char[]的重用

新的字符串必须进行一次ArrayCopy才能实现substring功能,所以肯定有新的内存生成


回来看了下实现

因为android studio开着,就看了下android下String.substring的实现,并截图发给了同学

public String substring(int start) {
        if (start == 0) {
            return this;
        }
        if (start >= 0 && start <= count) {
            return new String(offset + start, count - start, value);
        }
        throw indexAndLength(start);
    }
String(int offset, int charCount, char[] chars) {
        this.value = chars;
        this.offset = offset;
        this.count = charCount;
    }

利用成员变量offset保存下偏移量,直接把char[]引用给了新的String,没有申请内存

感叹好精妙的实现的同时,发现自己做错了



谁知道同学看了源代码后问我用的什么版本的jdk,和他那边的实现不一样

public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }

public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }
除了beginIndex=0是直接返回当前外,其他都进行ArrayCopy


是的!!!在JDK中new了新内存了!!!
不得不说,google程序员确实更高一筹


更正下,不是google的修改,是openjdk和jdk的区别



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值