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

我在 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?

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...