I have a class that contains a Random
object. I use the Random
object as part of a the overloaded hashCode()
and equals(Object o)
methods. I discovered that two java.util.Random
objects created with the same seed do not produce the same hash code nor does equals return true.
public class RandomTest extends TestCase {
public void testRandom() throws Exception {
Random r1 = new Random(1);
Random r2 = new Random(1);
assertEquals(r1.hashCode(), r2.hashCode()); //nope
assertEquals(r1, r2); //nope
}
}
I know the obvious work around is to use the seed plus nextSomething() for comparison(not perfect but it should work well enough). So my question is Why are two objects of type Random created with the same seed and at the same iteration not equal?
The java.util.Random
class doesn't override equals()
and hashCode()
methods, so hash code from Object
class is called, returning an address in memory for the object. So 2 different Random objects have 2 different hashCodes as they are actually different objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With