How do I get the seed from a Random in Java?

Marnix picture Marnix · May 14, 2011 · Viewed 23k times · Source

I am creating a deep clone for some object. The object contains a Random.

Is it good practice to retrieve the seed from the Random? If so, how? There isn't a Random.getSeed().

Answer

Madmenyo picture Madmenyo · Jul 17, 2015

A much more simple way of getting a seed is to generate one and store that as the seed. I am using this method for a game and want to give the player the option to generate the exact same world if he wishes too. So first I create a Random object without a seed then let that one generate a random number and use that in another random object as the seed. Whenever the player want the seed of the level I have it stored somewhere. By default the game is still random.

    Random rand = new Random();
    //Store a random seed
    long seed = rand.nextLong();
    //Set the Random object seed
    rand.setSeed(seed);

    //do random stuff...

    //Wonder what the seed is to reproduce something?
    System.out.println(seed);