public class CollectionTest{
public static void main(String args[]) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
代码运行结果是两个字符串对象的hash值是一样的,这是不是可以理解为内存中只有一个内容为hello的字符串对象,s1和s2引用都指向了这个对象?
这个例子确实是同一个
String
对象,用==
也是true
,但是并没有什么关系对于
String
,哈希码是用内容算出来的,一样的内容得到的哈希码也就是一样的也就是通常说的,
equals
返回true
,hashCode
也要一样