为什么hashCode()在所有连续执行中为对象返回相同的值? [英] Why hashCode() returns the same value for a object in all consecutive executions?

查看:139
本文介绍了为什么hashCode()在所有连续执行中为对象返回相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中尝试一些围绕对象相等的代码。正如我在某处读到的那样

I am trying some code around object equality in java. As I have read somewhere


hashCode()是一个由应用哈希函数。散列函数对于每个对象可以是不同的,但也可以是相同的。在对象级别,它返回对象的内存地址。

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次,连续。每次运行程序时,我都会获得与哈希码相同的值。

Now, I have sample program, which I run 10 times, consecutively. Every time i run the program I get the same value as hash code.

如果 hashCode()函数返回对象的内存位置,为什么java(JVM)在连续运行时将对象存储在相同的内存地址?

If hashCode() function returns the memory location for the object, how come the java(JVM) store the object at same memory address in the consecutive runs?

您能否给我一些见解和您对此问题的看法?

Can you please give me some insight and your view over this issue?

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

The Program I am running to test this behavior is below :

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

Every time I run this program the hash code value returned is 4072869.

推荐答案


<为什么java(JVM)在连续运行中将对象存储在相同的内存地址?

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

为什么不呢?非内核程序永远不会使用绝对内存地址,它们使用虚拟内存,每个进程都有自己的地址空间。因此,毫无疑问,确定性程序会在每次运行中将内容放置在同一位置。

Why wouldn't it? Non-kernel programs never work with absolute memory addresses, they use virtual memory where each process gets its own address space. So it's no surprise at all that a deterministic program would place stuff at the same location in each run.

这篇关于为什么hashCode()在所有连续执行中为对象返回相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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