Nathaniel Johnson
Nathaniel Johnson

Reputation: 4839

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?

Upvotes: 4

Views: 510

Answers (2)

Necreaux
Necreaux

Reputation: 9776

It appears that you are confusing the Random object with the results. The Random object is a random number generator, and not a random number. Comparing them makes no sense. Whatever you are trying to do should probably be accomplished a different way.

Upvotes: 0

Petr
Petr

Reputation: 6269

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.

Upvotes: 11

Related Questions