Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do two Random objects created with the same seed produce different results from hashcode()

Tags:

java

random

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?

like image 591
Nathaniel Johnson Avatar asked Dec 19 '22 04:12

Nathaniel Johnson


1 Answers

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.

like image 50
Petr Avatar answered May 24 '23 19:05

Petr