简体   繁体   中英

Creating an object of Random class or using Math.random() in order to generate random numbers

When you have imported java.util.Random, you can both generate random integers and random double two ways.

You could create an instance of the Random class

Random randomGenerator = new Random();

and then use it to generate a random integer or double that is greater than or equal to 0 but less than 10

int randomInteger = randomGenerator.nextInt(10);
double randomDouble = randomGenerator.nextDouble(10);

You can also use Math.random()

int randomInteger = (int)(Math.random() * 10)
double randomDouble = Math.random() * 10

I think both methods gives the exact same result. Is one of these two methods ever preferred rather than the other?

Math.random() uses the Random class. And it's basically calling nextDouble() on the Random object of the Math class.

However the first method is definitely easier to understand and use. And has more options then the Math class has. So I'd go with the Random class if you need a lot of Random numbers or if you need types other then double. And I'd use Math.random() when you only need a double between 0 and 1.

So basically there is no difference in how the methods work, they both use the Random class. So wich of the two you use depends on the situation as I stated above.

From the javadoc for the Math class on the random method:

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random()

Link to the javadoc page on Math.random(): https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

I hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM