我知道==在比较两个字符串时有一些问题。String.equals()似乎是一种更好的方法。嗯,我正在做JUnit测试,我倾向于使用assertEquals(str1, str2)。这是断言两个字符串包含相同内容的可靠方法吗?我将使用assertTrue(str1.equals(str2)),但这样您就无法看到失败时的预期值和实际值。
在相关的说明中,是否有人有一个页面或线程的链接,可以清楚地解释str1 == str2的问题?
我知道==在比较两个字符串时有一些问题。String.equals()似乎是一种更好的方法。嗯,我正在做JUnit测试,我倾向于使用assertEquals(str1, str2)。这是断言两个字符串包含相同内容的可靠方法吗?我将使用assertTrue(str1.equals(str2)),但这样您就无法看到失败时的预期值和实际值。
在相关的说明中,是否有人有一个页面或线程的链接,可以清楚地解释str1 == str2的问题?
当前回答
==运算符检查两个对象是否完全相同。
http://leepoint.net/notes-java/data/strings/12stringcomparison.html
String在java中是一个对象,所以它属于比较规则的范畴。
其他回答
==运算符检查两个对象是否完全相同。
http://leepoint.net/notes-java/data/strings/12stringcomparison.html
String在java中是一个对象,所以它属于比较规则的范畴。
在Java中比较字符串时,应该始终使用.equals()。
JUnit调用.equals()方法来确定方法assertEquals(Object o1, Object o2)中的相等性。
因此,使用assertEquals(string1, string2)绝对是安全的。(因为字符串是对象)
这里有一个链接到一个很棒的Stackoverflow问题,关于==和.equals()之间的一些差异。
public class StringEqualityTest extends TestCase {
public void testEquality() throws Exception {
String a = "abcde";
String b = new String(a);
assertTrue(a.equals(b));
assertFalse(a == b);
assertEquals(a, b);
}
}
简而言之,你可以有两个String对象,它们包含相同的字符,但是不同的对象(在不同的内存位置)。==操作符检查两个引用是否指向同一个对象(内存位置),但equals()方法检查字符是否相同。
通常,您感兴趣的是检查两个string是否包含相同的字符,而不是它们是否指向相同的内存位置。
assertEquals使用equals方法进行比较。还有一个不同的断言,assertSame,它使用==操作符。
To understand why == shouldn't be used with strings you need to understand what == does: it does an identity check. That is, a == b checks to see if a and b refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals method, on the other hand, can be overridden by classes. While its default behavior (in the Object class) is to do an identity check using the == operator, many classes, including String, override it to instead do an "equivalence" check. In the case of String, instead of checking if a and b refer to the same object, a.equals(b) checks to see if the objects they refer to are both strings that contain exactly the same characters.
Analogy time: imagine that each String object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use == to compare them it will return false because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return false. If I use equals, however, the equals method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return true.
字符串令人困惑的一点是,Java有一个“实习”字符串的概念,这(有效地)自动执行在你的代码中的任何字符串文字。这意味着如果你的代码中有两个等价的字符串字面量(即使它们在不同的类中),它们实际上都会引用相同的string对象。这使得==运算符返回true的次数比预期的要多。