问题描述
- 今天刷leetcode的一道回文字符串的时候用到了,跳过去看源码的时候,想到自己之前用这个方法的时候,会认为能截到endIndex的位置,所以记录一下。
问题分析
-
看String的源码咋说的
-
总的来说就是这是一个“左闭右开”区间, [beginIndex, endIndex)
- 备注:beginIndex可以等于endIndex,这时候截到的是空字符串。
一些乱七八糟的东西
- 整个方法
/**
* Returns a string that is a substring of this string. The
* substring begins at the specified {@code beginIndex} and
* extends to the character at index {@code endIndex - 1}.
* Thus the length of the substring is {@code endIndex-beginIndex}.
* <p>
* Examples:
* <blockquote><pre>
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or
* {@code endIndex} is larger than the length of
* this {@code String} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
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);
}
- String的值,final,字符数组
- new String(value, beginIndex, subLen)构造函数,用的Arrays.copyOfRange(value, offset, offset+count)实现
- 这个copy是深拷贝还是浅拷贝呢?
- 老了,睡觉先,头发要紧。如果明天不偷懒的话可能会接着看,溜