java - 为什么字符串类根据给定的字符串值创建哈希码?

标签 java string hashcode

哈希码是每个对象的唯一值,但为什么只有 String 类创建这样的哈希码。

public class StringSample 
{
public static void main(String[] args) 
{

String s1=new String("Example");
String s2=new String("Example");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());

}
}

结果

341682506
341682506

但是这个程序给出了不同的哈希码值

class Sample 
{
Sample(String str)
{

}
}
public class Mainclass
{
public static void main(String[] args) 
{
Sample s1=new Sample("Example");    
Sample s2=new Sample("Example");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}

}

结果:

2018699554
1311053135

最佳答案

你的假设是不正确的,参见。 http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode-- :

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.

但是,如果根据 equals(java.lang.Object) 方法两个对象相等,则它们必须具有相同的哈希码:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

在您的示例中,根据 equals(java.lang.Object)s1 等于 s2 > 方法,因此哈希码在不违反其一般契约的情况下不能不同:

  public static void main(String[] args) {
    String s1=new String("Example");
    String s2=new String("Example");

    System.out.println(s1.equals(s2)); // true
  }
<小时/>

更新:

关于您的更新并可能澄清我最初的答案。与 String 不同,您的 Sample 类可能既不会覆盖 hashCode() 也不会覆盖 equals(java.lang.Object)。这意味着,将使用 Java 的默认实现,它与当前实例的内存位置一起工作(我不知道确切的细节,但这确实应该为不同的对象生成不同的哈希码)。但是,这也意味着示例中的两个 Sample 对象的 s1.equals(s2) 将为 false

现在为什么String会覆盖equals(java.lang.Object)?因为人们会期望具有相同值的两个字符串(即“Example”)应该被代码视为相等。为了遵守 equals(java.lang.Object)hashCode() 之间的一般契约(参见上面的 javadocs),String现在还必须重写 hashCode() 方法,以便为相同的值生成相等的哈希代码。

简化:如果 String 不会重写 hashCode() 来生成观察到的输出,则两个不同的字符串不可能相等。

免责声明:请注意,Java 中的字符串通常是内部存储的,其行为与“常规”对象略有不同,但这只是为了完整性和进一步阅读。您可能还想了解 equals== 之间的差异。

关于java - 为什么字符串类根据给定的字符串值创建哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609728/

相关文章:

java - 由 : org. apache.logging.log4j.LoggingException 引起:log4j-slf4j-impl cannot be present with log4j-to-slf4j

Python:将str格式转换为可调用方法

python - 添加到矩阵中时修改字符串的大小写

java - 对于整数元组来说,什么是好的哈希函数?

Java Hashmap 两个相同的对象分开存储

java - 删除特定类型的所有实体

java - 在简单的多人 JAVA 游戏中从哪里开始使用套接字

java - Android -- Google+ 即时上传如何工作?

java - 将输入的文本转换为小写

java - 为什么库更喜欢在边缘情况下重新计算不可变对象(immutable对象)的哈希码?