java 对象hashcode,Java对象的默认hashCode()实现

I was trying to understand the hashCode() for Java's Object and saw the following code for Java Object's hashCode() method:

package java.lang;

public class Object {

// Some more code

public native int hashCode();

// Some other code

}

Now, we know that if we create a class it implicitly extends the Object class, and to do this I wrote a sample example:

package com.example.entity;

public class FirstClass {

private int id;

private String name;

// getters and setters

}

So, this class viz: FirstClass would be extending the Object class implicitly.

Main class:

package com.example.app.main;

import com.example.entity.FirstClass;

public class MainApp {

public static void main(String[] args) {

FirstClass fs = new FirstClass();

fs.setId(1);

fs.setName("TEST");

System.out.println("The hasCode for object fs is " + fs.hashCode());

}

}

As FirstClass is extending Object class implicitly, hence it would have Object classes' hashCode() method.

I invoked the hashCode() on FirstClass object , and as I haven't overridden the hashCode(), by theory it should invoke Object class's hashCode().

My doubt is:

As Object class don't have any implementation, how is it able to calculate the hash-code for any object?

In my case, when I run the program the hash-code which it returned was 366712642.

Can anyone help me understand this?

解决方案

Even though there are some answers here stating that the default implementation is "memory" based, this is plain wrong. This is not the case for a lot of years now.

Under java-8, you can do :

java -XX:+PrintFlagsFinal | grep hashCode

To get the exact algorithm that is used (5 being default).

0 == Lehmer random number generator,

1 == "somehow" based on memory address

2 == always 1

3 == increment counter

4 == memory based again ("somehow")

5 == read below

By default (5), it is using Marsaglia XOR-Shift algorithm, that has nothing to do with memory.

This is not very hard to prove, if you do:

System.out.println(new Object().hashCode());

multiple times, in a new VM all the time - you will get the same value, so Marsaglia XOR-Shift starts with a seed (always the same, unless some other code does not alter it) and works from that.

But even if you switch to some hashCode that is memory based, and Objects potentially move around (Garbage Collector calls), how do you ensure that the same hashCode is taken after GC has moved this object? Hint: indentityHashCode and Object headers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值