【发布时间】:2018-02-02 20:52:59
【问题描述】:
This question 之前有人问过,但没有真正回答。
如果 substring 方法创建了一个新对象,并且 this 是对象在池中“实习”,那么为什么 == 返回 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 方法相等
附:这是子串方法源码:
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);
}
附:这个问题已被标记为已被多个人提出并回答,但我在 Stack Overflow 上找不到一个实例,其中有人真正解释了为什么 substring(0) 将评估为 true。
【问题讨论】:
-
您没有
intern子字符串。str1.substring(5).intern() == str2.substring(5).intern(). -
@Apollonius。没有。
-
这是对象被“拘留”在池中 ...你认为这会自动发生吗?为什么?
-
感谢您的回复。我的困惑源于此处的问题陈述 (stackoverflow.com/questions/21606800/…) 及其答案。就像我说的,我必须回答一个非常相似的考试问题(我是学生),我不完全确定我是否理解它。我知道 substring() 方法将创建 2 个不同的对象,因此 == 操作将失败,但我不明白为什么在所述问题中声明 1 是正确的,但声明 2 是不正确的。显然,我错过了一些东西。
-
我终于找到了奇怪行为的答案,我在这里为可能有同样问题的其他人发布它。 substring() 方法(在 Java 7 中已更改)将始终返回一个新对象。唯一的例外是返回整个字符串 (substring(0))。然后,它将从池中返回,等式表达式 (==) 的计算结果为 true。