Java中hashCode()是如何计算的
java中hashCode()
方法返回什么值?
我读到它是一个对象的内存引用...new Integer(1)
的哈希值为 1; String("a")
的哈希值为 97。
我很困惑:它是 ASCII 还是什么类型的值?
What value does the hashCode()
method return in java?
I read that it is a memory reference of an object... The hash value for new Integer(1)
is 1; the hash value for String("a")
is 97.
I am confused: is it ASCII or what type of value is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
hashCode()
返回的值绝不保证是对象的内存地址。我不确定Object
类中的实现,但请记住,大多数类都会重写hashCode()
,这样两个实例在语义上是等效的(但不是相同的实例)将散列到相同的值。如果这些类可以在另一个数据结构(例如 Set)中使用,而该数据结构依赖于hashCode
与equals
一致,那么这一点尤其重要。无论如何,都不存在唯一标识对象实例的
hashCode()
。如果您想要基于底层指针的哈希码(例如在 Sun 的实现中),请使用 System.identityHashCode() - 这将委托给默认的 hashCode 方法,无论它是否已被覆盖。然而,即使是 System.identityHashCode() 也可以为多个对象返回相同的哈希值。请参阅注释以获取解释,但这里是一个示例程序,它不断生成对象,直到找到两个具有相同
System.identityHashCode()
的对象。当我运行它时,平均在向映射添加大约 86,000 个 Long 包装器对象(以及键的 Integer 包装器)后,它会快速找到两个匹配的 System.identityHashCode()。输出示例:
The value returned by
hashCode()
is by no means guaranteed to be the memory address of the object. I'm not sure of the implementation in theObject
class, but keep in mind most classes will overridehashCode()
such that two instances that are semantically equivalent (but are not the same instance) will hash to the same value. This is especially important if the classes may be used within another data structure, such as Set, that relies onhashCode
being consistent withequals
.There is no
hashCode()
that uniquely identifies an instance of an object no matter what. If you want a hashcode based on the underlying pointer (e.g. in Sun's implementation), useSystem.identityHashCode()
- this will delegate to the defaulthashCode
method regardless of whether it has been overridden.Nevertheless, even
System.identityHashCode()
can return the same hash for multiple objects. See the comments for an explanation, but here is an example program that continuously generates objects until it finds two with the sameSystem.identityHashCode()
. When I run it, it quickly finds twoSystem.identityHashCode()
s that match, on average after adding about 86,000 Long wrapper objects (and Integer wrappers for the key) to a map.Example output:
哈希码是一个整数值,表示调用它的对象的状态。这就是为什么设置为 1 的
Integer
将返回哈希码“1”,因为Integer
的哈希码及其值是相同的。字符的哈希码等于它的 ASCII 字符代码。如果您编写自定义类型,则您有责任创建一个良好的hashCode
实现,以最好地表示当前实例的状态。A hashcode is an integer value that represents the state of the object upon which it was called. That is why an
Integer
that is set to 1 will return a hashcode of "1" because anInteger's
hashcode and its value are the same thing. A character's hashcode is equal to it's ASCII character code. If you write a custom type you are responsible for creating a goodhashCode
implementation that will best represent the state of the current instance.如果您想了解它们是如何实现的,我建议您阅读源代码。如果您使用的是 IDE,您只需 + 您感兴趣的方法即可查看该方法是如何实现的。如果您无法做到这一点,您可以通过谷歌搜索来源。
例如,Integer.hashCode() 实现为
String.hashCode()
If you want to know how they are implmented, I suggest you read the source. If you are using an IDE you can just + on a method you are interested in and see how a method is implemented. If you cannot do that, you can google for the source.
For example, Integer.hashCode() is implemented as
and String.hashCode()
hashCode()
方法通常用于识别对象。我认为Object
实现返回对象的指针(不是真正的指针,而是唯一的 id 或类似的东西)。但大多数类都会重写该方法。就像String
类一样。两个 String 对象具有不同的指针,但它们是相等的:我认为
hashCode()
最常见的用途是在Hashtable
、HashSet
中,等等..Java API 对象 hashCode()
编辑:(由于最近的否决,并且基于我读到的有关 JVM 参数的文章)
使用 JVM 参数
-XX:hashCode
您可以更改方式hashCode 的计算方式(请参阅 Java 专家通讯的 第 222 期)。The
hashCode()
method is often used for identifying an object. I think theObject
implementation returns the pointer (not a real pointer but a unique id or something like that) of the object. But most classes override the method. Like theString
class. Two String objects have not the same pointer but they are equal:I think the most common use for
hashCode()
is inHashtable
,HashSet
, etc..Java API Object hashCode()
Edit: (due to a recent downvote and based on an article I read about JVM parameters)
With the JVM parameter
-XX:hashCode
you can change the way how the hashCode is calculated (see the Issue 222 of the Java Specialists' Newsletter).不。大约 14 年前,
Object.hashCode()
用于返回内存地址。从那以后就没有了。它是什么完全取决于您正在谈论的类以及它是否覆盖了`Object.hashCode()。
No.
Object.hashCode()
used to return a memory address about 14 years ago. Not since.What it is depends entirely on what class you're talking about and whether or not it has overridden `Object.hashCode().
来自 OpenJDK 源 (JDK8):
使用默认值 5 生成哈希码:
一些常量数据和随机生成的数字,每个线程启动一个种子:
然后,此函数创建 hashCode(默认为 5,如上所述):
所以我们可以请注意,至少在 JDK8 中,默认值设置为随机线程特定。
From OpenJDK sources (JDK8):
Use default of 5 to generate hash codes:
Some constant data and a random generated number with a seed initiated per thread:
Then, this function creates the hashCode (defaulted to 5 as specified above):
So we can see that at least in JDK8 the default is set to random thread specific.
Object.hashCode(),如果内存服务正确(检查 java.lang.Object 的 JavaDoc),则依赖于实现,并且会根据对象而变化(Sun JVM 从对象的引用值中派生出该值) )。
请注意,如果您正在实现任何重要的对象,并且希望将它们正确存储在 HashMap 或 HashSet 中,则必须重写 hashCode() 和 equals()。 hashCode() 可以做任何你想做的事情(这是完全合法的,但返回 1 并不是最理想的。),但重要的是,如果你的 equals() 方法返回 true,那么两个对象的 hashCode() 返回的值是相等的。
对 hashCode() 和 equals() 的混淆和缺乏理解是错误的一大来源。确保您完全熟悉 Object.hashCode() 和 Object.equals() 的 JavaDocs,我保证所花费的时间是值得的。
Object.hashCode(), if memory serves correctly (check the JavaDoc for java.lang.Object), is implementation-dependent, and will change depending on the object (the Sun JVM derives the value from the value of the reference to the object).
Note that if you are implementing any nontrivial object, and want to correctly store them in a HashMap or HashSet, you MUST override hashCode() and equals(). hashCode() can do whatever you like (it's entirely legal, but suboptimal to have it return 1.), but it's vital that if your equals() method returns true, then the value returned by hashCode() for both objects are equal.
Confusion and lack of understanding of hashCode() and equals() is a big source of bugs. Make sure that you thoroughly familiarize yourself with the JavaDocs for Object.hashCode() and Object.equals(), and I guarantee that the time spent will pay for itself.
定义:String hashCode() 方法以整数形式返回 String 的 hashcode 值。
语法:
public int hashCode()
哈希码使用以下公式计算
示例:
例如,如果您想计算字符串“abc”的哈希码,那么我们有以下详细信息
因此哈希码值将计算为:
因此“abc”的哈希码值为96354
Definition: The String hashCode() method returns the hashcode value of the String as an Integer.
Syntax:
public int hashCode()
Hashcode is calculated using below formula
Example:
For example if you want to calculate hashcode for string "abc" then we have below details
So the hashcode value will be calculated as:
So the hashcode value for 'abc' is 96354
我很惊讶没有人提到这一点,但尽管它对于任何非
Object
类来说都是显而易见的,但您的第一个操作应该是阅读许多类的源代码.hashcode()
是只是从Object
扩展而来,在这种情况下,根据您的 JVM 实现,可能会发生一些不同的有趣的事情。Object.hashcode()
调用System.identityHashcode(object)
。事实上,在内存中使用对象地址已经是古老的历史,但许多人没有意识到他们可以控制这种行为以及如何通过jvm参数
-XX:hashCode=N
计算Object.hashcode()
> 其中 N 可以是 [0-5] 中的数字...根据应用程序的不同,当调用
.hashcode()
时,您可能会看到意外的性能影响,当发生这种情况时,您可能正在使用共享全局状态和/或块的算法之一。I'm surprised that no one mentioned this but although its obvious for any non
Object
class your first action should be to read the source code for many classes.hashcode()
is simply extended fromObject
in which case there are several different interesting things that may happen depending on your JVM implementation.Object.hashcode()
calls toSystem.identityHashcode(object)
.Indeed using object address in memory is ancient history but many do not realise they can control this behaviour and how
Object.hashcode()
is computed via jvm argument-XX:hashCode=N
where N can be a number from [0-5]...Depending on an application you may see unexpected performance hits when
.hashcode()
is called, when that happens it is likely you are using one of the algorithms that shares global state and/or blocks.来自 Javadoc:
https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#哈希码--
From the Javadoc:
https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--
根据javaDoc的“对象的内部地址转换为整数”。因此很明显,hashCode() 方法不会按原样返回对象的内部地址。下面提供了链接。
https://docs.oracle。 com/javase/8/docs/api/java/lang/Object.html#hashCode--
要清除它,请参阅以下示例代码:
每个对象都有唯一的内存位置,如果对象的 hashCode 方法返回内存位置,则对象的 hashCode 也是唯一的,但如果我们运行上面的示例代码,则某些对象具有相同的 hashcode 值,而某些对象具有唯一的 hashcode 值。
所以我们可以说 Object 类的 hashCode 方法不返回内存位置。
According to javaDoc of "internal address of the object is converted into an integer". So it is clear that hashCode() method do not return internal address of object as it is. Link is provided below.
https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--
To clear it please see following sample code:
Each Object has unique memory location , and if Object's hashCode method return memory location then hashCode of Object is also unique but if we run above sample code then some Objects have same hashcode value and some have unique hashcode value.
So we can say that hashCode method from Object class does not return memory location.