java - 为什么 String 对象的 hashCode() 与自定义类对象的 hashCode() 不同?

标签 java

为什么stringObject的hashcode是我提供的字符串?

String s = new String(); // here the hascode is 0. 

但是当我获得我创建的某个对象的哈希码时。

testClass o = new testClass(); // the hashcode is some random number.

我的问题是两者有什么区别?我的理解是 hashCode() 来自 Object 类,它是所有类的母亲。

最佳答案

Why is the hashcode of stringObject is the string I provided? ex. String s = new String("hello"); // here the hascode is hello.

这不是真的

hashCode() 是一个 int 数字

您似乎混淆了 hashcode() 和 toString()

如果你想检查hashcode()

String str = "hello";
System.out.println(str.hashcode());//will print some int number
System.out.println(str);//will invoke toString() which will return `hello`

关于java - 为什么 String 对象的 hashCode() 与自定义类对象的 hashCode() 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945329/

相关文章:

java - 如何在 java 中打印 jpanel?

java - 有关Executors.newSingleThreadExecutor()的问题

java - 如何在 Android 应用程序中保留我的主题设置?

java - java中的聚合

java - IntelliJ IDEA 中通过 Gradle 的 OptaPlanner 依赖项

java - 使用(重新)验证、重绘后 Swing ContentPane 未更新

java - hibernate 恩弗斯 : Log user ip address

java - 复制并粘贴到 javafx 应用程序中嵌入的 codemirror.js

java - 如果数据库表的 ans 列为空,我想给出 'edit-link i.e <a>edit</a>'

java - Sqlite 列到字符串数组