JavaSE字符串池

JavaSE字符串池,java,string,string-pool,Java,String,String Pool,我不明白为什么下面的代码返回“false” 我读过“字符串是不可变的,文本是池化的”。执行trim(),z将z=“Hello World”,然后为什么输出不是true?您将指针与对象进行比较,这将是不同的。对于字符串,应使用: x.equals(z) 您将指针与对象进行比较,这将是不同的。对于字符串,应使用: x.equals(z) 这是因为字符串是不可变的!因此,trim()方法返回具有不同引用的String的新实例。您可以通过查看源代码来查看它 public String trim()

我不明白为什么下面的代码返回“false”


我读过“字符串是不可变的,文本是池化的”。执行
trim()
,z将
z=“Hello World”
,然后为什么输出不是
true

您将指针与对象进行比较,这将是不同的。对于字符串,应使用:

x.equals(z)

您将指针与对象进行比较,这将是不同的。对于字符串,应使用:

x.equals(z)

这是因为字符串是不可变的!因此,
trim()
方法返回具有不同引用的
String
的新实例。您可以通过查看源代码来查看它

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;

    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}

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); // new instance!
}
公共字符串修剪(){
int len=value.length;
int st=0;
char[]val=值;
while((st
这是因为字符串是不可变的!因此
trim()
方法返回一个新的
String
实例,该实例具有不同的引用。您可以通过查看源代码来查看它

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;

    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}

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); // new instance!
}
公共字符串修剪(){
int len=value.length;
int st=0;
char[]val=值;
while((st
This()可以帮助你!!This()可以帮助你!!为什么不同?“Hello World”在字符串池中,x和z指向同一个字符串
x
y
是不同的
String
对象,只有相同的内容。要比较内容是否相等,必须使用
equals()
。为什么不同?“Hello World”在字符串池中,x和z指向同一字符串
x
y
是不同的
String
对象,只有内容相同。要比较内容是否相等,必须使用
equals()