先看一个简单的程序,一般我们打印对象,大部分是下面的情况,可能会重写下toString()方法
public static void main(String[] args) {
Frolan frolan = new Frolan();
System.out.println(frolan);
}
打印结果
com.msedu.wisdomquestion.admin.entity.Frolan@2b80d80f
这个结果其实是调用了Object.toString打印出来的,就是类路径名+@+hashCode()的16进制数
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
这里的hashCode()是一个native方法,其实就是我们要的地址值,当然,这是有前提条件的,我们通过源码来看一下
static inline intptr_t get_next_hash(Thread * Self, oop obj) {
intptr_t value = 0 ;
if (hashCode == 0) {
// This form uses an unguarded global Park-Miller RNG,
// so it's possible for two threads to race and generate the same RNG.
// On MP system we'll have lots of RW access to a global, so the
// mechanism induces lots of coherency traffic.
value = os::random() ;
} else
if (hashCode == 1) {
// This variation has the property of being stable (idempotent)
// between STW operations. This can be useful in some of the 1-0
// synchronization schemes.
intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3 ;
value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
} else
if (hashCode == 2) {
value = 1 ; // for sensitivity testing
} else
if (hashCode == 3) {
value = ++GVars.hcSequence ;
} else
if (hashCode == 4) {
value = cast_from_oop<intptr_t>(obj) ;
} else {
// Marsaglia's xor-shift scheme with thread-specific state
// This is probably the best overall implementation -- we'll
// likely make this the default in future releases.
unsigned t = Self->_hashStateX ;
t ^= (t << 11) ;
Self->_hashStateX = Self->_hashStateY ;
Self->_hashStateY = Self->_hashStateZ ;
Self->_hashStateZ = Self->_hashStateW ;
unsigned v = Self->_hashStateW ;
v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
Self->_hashStateW = v ;
value = v ;
}
value &= markOopDesc::hash_mask;
if (value == 0) value = 0xBAD ;
assert (value != markOopDesc::no_hash, "invariant") ;
TEVENT (hashCode: GENERATE) ;
return value;
}
大概意思就是,会根据不同的hashCode返回不同的结果
hashCode=0,随机数
hashCode=1,对象内存地址做位运算、异或运算后的值
hashCode=2,固定值1
hashCode=3,返回递增序列数值
hashCode=4,返回对象内存地址
hashCode=其他值,简单理解为移位寄存器,线程安全
我们来模拟一下,设置JVM启动参数,-XX:hashCode=2
// -XX:hashCode=2
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
Frolan frolan = new Frolan();
System.out.println(frolan.hashCode());
}
}
打印结果
1
1
1
我们不设置启动参数,默认就是返回对象的内存地址,但打印出来一定是内存地址?
这个不一定,如果我们重写了hashCode()方法,那就不是了
那如果我们重写了hashCode()方法,要想打印对象的内存地址,这时候可以怎么搞?
可以用System.identityHashCode()方法
@Override
public int hashCode() {
return Objects.hashCode(id, name);
}
public static void main(String[] args) {
Frolan frolan = new Frolan();
System.out.println(frolan);
System.out.println(System.identityHashCode(frolan));
}
打印结果
Frolan{id=null, name='null'}
729864207
标签:Java,Self,打印,value,hashCode,Frolan,frolan,内存地址
From: https://www.cnblogs.com/huozhonghun/p/17119446.html