给定两个字符串变量s1
和s2
,是否有可能为(s1 != s2)
真而同时(s1.equals(s2))
也为真?
我会说不,因为如果由于“h”String s1 = "Hello";
与 String s2 = "hello";
“H”而不相等,但第二部分不可能是真的,因为当作为对象进行比较时,它们也不相同。这有意义吗?
是的。只需确保它们相同但引用不同(即不要实习或通过文字使用字符串池)。这是一个例子:
String s1="teststring";
String s2 = new String("teststring");
System.out.println(s1 != s2); //prints true, different references
System.out.println(s1.equals(s2)); //true as well, identical content.
对于两个字符串s1
和s2
,
(s1 != s2) //Compares the memory location of where the pointers,
//s1 and s2, point to
(s1.equals(s2) //compares the contents of the strings
所以,对于s1 = "Hello World"
和s2 = "Hello World"
:
(s1 == s2) //returns false, these do not point to the same memory location
(s1 != s2) //returns true... because they don't point to the same memory location
(s1.equals(s2)) //returns true, the contents are identical
!(s1.equals(s2)) //returns false
在 和 的情况下s1 = "Hello World"
,s2 = "hello world"
(s1.equals(s2)) //This returns false because the characters at index 0
//and 6 are different
最后,如果你想要一个不区分大小写的比较,你可以这样做:
(s1.toLowerCase().equals(s2.toLowerCase())) //this will make all the characters
//in each string lower case before
//comparing them to each other (but
//the values in s1 and s2 aren't
//actually changed)
String s1 = new String("Hello");
String s2 = new String("Hello");
s1 == s2
返回false
s1.equals(s2)
返回true
因此,是的,这是可能的,因为默认情况下这些字符串不会在公共池内存中保存/检查,因为不是文字。