0 java
可能重复:
字符串相等与位置相等
public class AboutStrings{
public static void main(String args[]){
String s1="hello";
String s2="hel";
String s3="lo";
String s4=s2+s3;
//to know the hash codes of s1,s4.
System.out.println(s1.hashCode());
System.out.println(s4.hashCode());
// these two s1 and s4 are having same hashcodes.
if(s1==s4){
System.out.println("s1 and s4 are same.");
}else
System.out.println("s1 and s4 are not same.");
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,即使s1和s4引用同一个对象(具有相同的哈希码),
它是打印s1和s4是不一样的.
任何人都可以详细解释为什么它表现得像这样吗?
仅仅因为两个对象具有相同的散列码也不能说他们是同一个对象(你用==对象的身份检查!).
你可能想打电话
s1.equals(s4)
Run Code Online (Sandbox Code Playgroud)
相反 - 但即使这样,两者都可以具有相同的哈希码而不相等:两个相等的对象必须具有相同的哈希码(在集合中正常工作等),但反之亦然.
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |