您的位置:首页 > 编程语言 > Java开发

JDK String 源码学习,这个构造方法写的有点逻辑不太清晰

2016-01-25 16:39 519 查看
今天无意间看到String的一个构造方法,总感觉有点不是太舒服。源码如下(JDK 1.8 ):

public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// 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);
}


改成如下这种不知道是不是考虑周全了:

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);
}

//necessary?
if (count == 0) {
this.value = "".value;
return;
}

this.value = Arrays.copyOfRange(value, offset, offset + count);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JDK 1.8 源码 String