java哈希代码和与字符串的equals关系
String s1 = new String("abc");//it is created at heap area
String s2 = "abc";//it is created string constant pool
System.out.println(s1==s2);//false
System.out.println(s1.hashCode());same hashCode
System.out.println(s2.hashCode());same hashCode
最后两行给出了相同的hashCode()
,但对象不同。创建s1对象时,它在堆区域中创建,s2对象在字符串常量池中创建。但两者都给出了相同的哈希代码。i、 我的怀疑是什么
# 1 楼答案
{a1}州
因为
String
对象具有相同的字符,所以它们的哈希码是相等的# 2 楼答案
因为
String#hashCode()
基于字符内容,而不是对象标识: