Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can default hashCode act as entropy source?

Tags:

java

A very strange question: if I needs only one random number for one object, can we use the hashCode as entropy source instead of creating a new Java.util.Random object and then call nextInr()?

like image 682
Gstestso Avatar asked Aug 10 '26 19:08

Gstestso


1 Answers

The default implementation of hashCode() is to return the object's identity hash which is provided by the JVM and probably not so random. If hashCode() has been overridden, which is quite often the case, the return value is even less random and any implementation that returns a random number for hashCode() (even if it is the same for every call on one instance) will most probably break the contract that has been defined for equals() and hashCode();

From the JavaDoc:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

So I'd recommend to keep using java.util.Random (you could use a single instance) or something different, but not hashCode().

like image 199
Thomas Avatar answered Aug 13 '26 09:08

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!