Java生成随机数的函数有哪些?有漏洞吗?奇趣编程整理了以下这些。
1、java.lang.Math
示例 int randomWithMathRandom = (int) ((Math.random() * (max – min)) + min);
2、java.util.Random
示例
Random random = new Random();
int randomWithNextInt = random.nextInt();
3、random.ints
示例:IntStream unlimitedIntStream = random.ints();
4、java.util.concurrent.ThreadLocalRandom
int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current().nextInt(min, max);
int randomWithThreadLocalRandom = ThreadLocalRandom.current().nextInt();
int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current().nextInt(max);
IntStream streamWithThreadLocalRandom = ThreadLocalRandom.current().ints();
5、java.util.SplittableRandom
SplittableRandom splittableRandom = new SplittableRandom();
int randomWithSplittableRandom = splittableRandom.nextInt(min, max);
IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max);
6、java.security.SecureRandom
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandom = secureRandom.nextInt();
int randomWithSecureRandomWithinARange = secureRandom.nextInt(max – min) + min;
7、org.apache.commons.math3.random.RandomDataGenerator
RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max);
8、it.unimi.dsi.util.XoRoShiRo128PlusRandom
XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom();
int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max – min) + min;
Java的随机数生成函数常用的有以上几个,当然大家也可以自己设计一种算法来生成随机数。