java中String类的substring的小细节

String类的substring()方法实现返回一个字符串,该字符串是此字符串的子字符串。

根据源码可以看出如果当形参为0时返回的仍然是但前的字符串对象,并没有创建新的对象:

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



小栗子:

class MyMian {
 public static void main(String[] args) {
  String str1 ="hello";
  String str2 = str1.substring(0);
  System.out.println(str2==str1);
 }
}

运行结果为true


猜你喜欢

转载自blog.csdn.net/m_target/article/details/80394190