如果两个对象具有相同的哈希码,那么它们的内存地址如何? [英] if two objects have same hashcode then what about their memory addresses
问题描述
如果两个相同类的对象在Java中具有相同的hashCode,那么它们将如何存储在 HashMap
/ HashTable
?散列码和内存地址的实际体系结构是什么? hashCode在内存中的位置?
示例:有一个类 A
。当创建对象 a1
和 a2
时,它们将代表一些内存地址,但是我每次都会覆盖哈希码。当我阅读一篇文章时,我发现哈希码函数从内存地址生成哈希码。这意味着如果散列码相同,则内存地址将相同。请清除我的疑问。
public class A {
@Override
public int hashCode(){
返回1;
public static void main(String args []){
A a1 = new A();
A a2 = new A();
System.out.println(a1.hashCode());
System.out.println(a2.hashCode());
}
}
没有两个对象(同时存在)可以具有相同的内存地址。
它们可以具有相同的哈希码,尽管 hashCode
实现尝试避免这种情况。并且 hashCode
的默认实现不必基于对象的内存地址(尽管可以)。 b
$ b
因此,如果两个对象具有相同的哈希码,则不能认为它们具有相同的内存地址。事实上,如果两个变量引用不同的对象(即将它们与 em>在 If two objects of the same class have the same hashCode in Java then how would they be stored in a Example: There is a class
No two objects (that exist at the same time) can have the same memory address. They can have the same hash code, though So if two objects have the same hash code, you can't assume that they have the same memory address. In fact, if two variables refer to different objects (i.e. comparing them with The article you read about hash codes being based on memory addresses was referring to the default implementation of the 这篇关于如果两个对象具有相同的哈希码,那么它们的内存地址如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ==
返回 false
)进行比较, 没有相同的地址。
Object
类中实现 hashCode
方法。如果在子类中重写 hashCode
,则不再使用该默认实现。你的 return 1
与内存地址无关。HashMap
/ HashTable
? What is the actual architecture for hashcode and memory address. Where does hashCode reside in memory?A
. when creating objects a1
and a2
then they will represent some memory address but I overrode hashcode every time same. When I read an article then I found that hashcode functions generate a hashcode from the memory address. this means the memory address will same if hashcode is same. Please clear my doubt. public class A {
@Override
public int hashCode() {
return 1;
}
public static void main(String args[]) {
A a1 = new A();
A a2 = new A();
System.out.println(a1.hashCode());
System.out.println(a2.hashCode());
}
}
hashCode
implementations try to avoid that. And the default implementation of hashCode
doesn't have to be based on the object's memory address (though it can be).==
returns false
), they definitely do not have the same address.hashCode
method in the Object
class. If you override hashCode
in a subclass, you're not using that default implementation anymore. Your return 1
has nothing to do with memory addresses.