如果两个对象具有相同的哈希码,那么它们的内存地址如何? [英] if two objects have same hashcode then what about their memory addresses

查看:213
本文介绍了如果两个对象具有相同的哈希码,那么它们的内存地址如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个相同类的对象在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

因此,如果两个对象具有相同的哈希码,则不能认为它们具有相同的内存地址。事实上,如果两个变量引用不同的对象(即将它们与 == 返回 false )进行比较, 没有相同的地址。

em>在 Object 类中实现 hashCode 方法。如果在子类中重写 hashCode ,则不再使用该默认实现。你的 return 1 与内存地址无关。


If two objects of the same class have the same hashCode in Java then how would they be stored in a HashMap / HashTable? What is the actual architecture for hashcode and memory address. Where does hashCode reside in memory?

Example: There is a class 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());
    }
}

解决方案

No two objects (that exist at the same time) can have the same memory address.

They can have the same hash code, though 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).

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 == returns false), they definitely do not have the same address.

The article you read about hash codes being based on memory addresses was referring to the default implementation of the 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.

这篇关于如果两个对象具有相同的哈希码,那么它们的内存地址如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆