Ben Chuanlong Du's Blog

It is never too late to learn.

Understand System.identityHashCode in Java

Tips and Traps

  1. You cannot get the address of an object in Java (without hacking). System.identityHashCode(obj) is the next best thing you can have. This trick (combined with the timestamp) is used to generate default seed for random number generators in Java.
In [4]:
import org.apache.commons.math3.random.RandomDataGenerator
import collection.JavaConverters._
val rng1 = new RandomDataGenerator()
val rng2 = new RandomDataGenerator()
Out[4]:
import org.apache.commons.math3.random.RandomDataGenerator

import collection.JavaConverters._

rng1: RandomDataGenerator = org.apache.commons.math3.random.RandomDataGenerator@254a5d85
rng2: RandomDataGenerator = org.apache.commons.math3.random.RandomDataGenerator@e18d0ae
In [5]:
System.identityHashCode(rng1)
Out[5]:
res4: Int = 625630597
In [6]:
System.identityHashCode(rng2)
Out[6]:
res5: Int = 236507310

References

In [ ]:

Comments