您的位置:首页 > 移动开发 > Android开发

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

2014-09-25 00:25 387 查看
今天有幸去搜狗霸笔,有一题很有意思

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的区别
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐