子串方法 -​​ 等式测试失败

时间:2018-02-02 20:52:59

标签: java substring equality

之前已经问过{p> This question,但没有真正回答。

如果substring方法创建了一个新对象,那么对象是" interned"在池中,为什么==返回false。这是我的代码:

public class StringTest {
    public static void main(String[] args) {
        String str1 = "The dog was happy";
        String str2 = "The hog was happy";
        System.out.println(str1.substring(5));// just to make sure
        System.out.println(str2.substring(5));

        if (str1.substring(5) == str2.substring(5)) {
            System.out.println("Equal using equality operator");
        } else {
            System.out.println("Not equal using equality operator");
        }

        if (str1.substring(5).equals(str2.substring(5))) {
            System.out.println("Equal using equals method");
        } else {
            System.out.println("Not equal using equals method");
        }

    }
}

输出是:1。og很高兴2. og很高兴3.不等于使用等于运算符4.等于使用equals方法

P.S。这是substring方法的源代码:

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

P.S。这个问题已被标记为由几个人提出并回答,但我在Stack Overflow上找不到一个实例,其中有人实际解释了为什么substring(0)将评估为true。

1 个答案:

答案 0 :(得分:2)

答案在于你自己的问题。

尝试执行以下操作:

String str1 = "The dog was happy";
 String str2 = "The dog was happy";
 if (str1 == str2) 
 {
    System.out.println("Equal using equality operator");
 } 
  else 
 {
      System.out.println("Not equal using equality operator");
 }

你将得到&#34;等于使用相等运算符&#34;。原因是你已经将str1和str2都声明为字符串文字,并且应用了实习池的概念。

现在,当您根据String类定义执行str1.substring(5)时,它返回一个对象,而不是文字。因此==给出错误的结果。

String class Substring方法:

return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);

如果你想让==处理子字符串,请在子字符串上使用intern()方法。

变化: if (str1.substring(5) == str2.substring(5))

if (str1.substring(5).intern() == str2.substring(5).intern())

一个很好的文档来理解字符串创建和池的细节:https://www.journaldev.com/797/what-is-java-string-pool

相关问题