加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么hashCode()在所有连续执行中为对象返回相同的值?

发布时间:2020-12-14 16:44:53 所属栏目:Java 来源:网络整理
导读:我在 java中尝试一些关于对象相等性的代码.正如我在某处读过的 hashCode() is a number which is generated by applying the hash function. Hash Function can be different for each object but can also be same. At the object level,it returns the mem
我在 java中尝试一些关于对象相等性的代码.正如我在某处读过的

hashCode() is a number which is generated by applying the hash function. Hash Function can be different for each object but can also be same. At the object level,it returns the memory address of the object.

现在我有一个样例程序,我连续运行10次.每次我运行程序,我得到与哈希码相同的值.

如果hashCode()函数返回对象的内存位置,那么java(JVM)在连续运行中如何将对象存储在同一个内存地址?

你能给我一些洞察力和你对这个问题的看法吗?

我正在运行的测试这个行为的程序如下:

public class EqualityIndex {

    private int index;

    public EqualityIndex(int initialIndex) {
       this.index = initialIndex;
    }

    public static void main(String[] args) {
        EqualityIndex ei = new EqualityIndex(2);
        System.out.println(ei.hashCode());
    }

}

每次运行此程序时,返回的哈希码值为4072869.

解决方法

how come the java(JVM) store the object at same memory address in the consecutive runs?

为什么不呢非内核程序从不使用绝对内存地址,它们使用虚拟内存,每个进程都有自己的地址空间.所以毫无疑问,一个确定性的程序会将东西放在每个运行的同一位置.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读