jeudi 23 avril 2015

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

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?




Aucun commentaire:

Enregistrer un commentaire