String.subString()方法的执行过程,
分享于 点击 26391 次 点评:259
String.subString()方法的执行过程,
一次面试遇到一个问题, 问我subString()方法是怎么实现的, 这个....有点考住我了, 含含糊糊的回答了一下, 因为毕竟没看过源码, 就按着自己的理解去回答.
今天看了下subString方法的实现:
其实String类是把字符串转换成了char[]数组来进行存储的.
如: String str = "abcdefg";
其实是: char[] c = {"a","b","c","d","e","f","g"};
subString()方法的实现:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {<span > </span>// 这里的value是将str转换成了char[]这个数组.
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex; // 这里计算出截取的字符串的长度
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen); // 这里如果是从0到结束的个元素截取的话就直接返回当前对象, 如果不是就根据要截取的元素位置进行截取,并new一个新的String对象返回.
}
String()的构造方法:
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); // 这里去调用Arrays.copyOfRange(原字符串,截取起始位置,起始位置+截取的长度<这里应该可以直接传截取的长度过去吧, 不知道为什么还要加上其实位置, 因为在这个方法中也是用这个参数-起始位置获得的截取的长度, 感觉有点多此一举呢, 不管吧, 反正就是这么的.>)方法来返回截取的字符串
}
Arrays.copyOfRange()方法:
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from; // 这里又重新计算了一下截取的长度
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];<span > </span>// 创建一个要截取长度的char[]数组
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength)); // 调用Systtem.arraycopy()这个静态方法, 让它来实现数组之间的复制. 接下来对这个方法的参数进行描述: original是源数据, form是截取的起始位置, copy是截取的新的char[]数组, 0表示目标数组插入的起始位置, 最后一个参数是要复制的长度(这里使用Math.min(ex1, ex2)来对两个数值进行比较, 如果相同就返回相同的, 否则就返回两个中小的那一个). 这个方法的实现过程是这样的: 将original数组中从form开始到(from+最后一个参数-1)之间的数据拷贝到copy数组中, 从0的位置开始插入.
return copy;// 返回新数组
}
这就是String的subString()方法的执行过程. 其实主要是System.arraycopy()这个静态方法比较关键, 这里就没有跟踪到arraycopy()这个方法具体是怎么实现的了, 有知道的童鞋可以给我分享一下, 大家互相学习.这个方法应该是平时开发过程中也可能经常用到来操作数组的, 学习了.
相关文章
- 暂无相关文章
用户点评