看String的源码
看到
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
当时就想到2个问题,第一个是endIndex可以等于count,因为他的判定条件是Index > count,第二个就是他return的是
new String(offset + beginIndex, endIndex - beginIndex, value)
再看看这个构造方法
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
也就是char value[]是共享的,只是调整offset和count的值来完成截取的。
不明白这样做的目的是什么,有什么好处,新截出来的字符串不是有浪费空间的嫌疑?
然后查阅网上其他人的关于substring的文章
参考博客:http://blog.youkuaiyun.com/bzwm/article/details/5844045
发现这个substring方法还是要小心点用