您好,登录后才能下订单哦!
java.util.Random
类在 Java 中被广泛用于生成随机数。以下是 Random
类中一些常用的方法:
nextInt()
: 生成一个介于 0(包括)和指定整数(不包括)之间的随机整数。
int randomInt = random.nextInt();
int randomIntInRange = random.nextInt(upperBound);
nextInt(int bound)
: 生成一个介于 0(包括)和指定整数(不包括)之间的随机整数。
int randomInt = random.nextInt(10); // 生成 0 到 9 之间的随机整数
nextLong()
: 生成一个介于 0(包括)和指定长整数(不包括)之间的随机长整数。
long randomLong = random.nextLong();
long randomLongInRange = random.nextLong(upperBound);
nextDouble()
: 生成一个介于 0(包括)和 1(不包括)之间的随机双精度浮点数。
double randomDouble = random.nextDouble();
nextFloat()
: 生成一个介于 0(包括)和 1(不包括)之间的随机单精度浮点数。
float randomFloat = random.nextFloat();
nextBoolean()
: 生成一个随机的布尔值,true
或 false
。
boolean randomBoolean = random.nextBoolean();
nextBytes(byte[] bytes)
: 将随机字节填充到指定的字节数组中。
byte[] randomBytes = new byte[10];
random.nextBytes(randomBytes);
setSeed(long seed)
: 使用指定的种子值初始化随机数生成器。使用相同的种子可以确保每次运行程序时生成的随机数序列相同。
long seed = System.currentTimeMillis();
random.setSeed(seed);
shuffle(int[] array)
: 使用默认随机源对指定数组中的元素进行随机排序。
int[] array = {1, 2, 3, 4, 5};
random.shuffle(array);
shuffle(int[] array, int fromIndex, int toIndex)
: 使用默认随机源对指定数组中的元素进行随机排序,从 fromIndex
(包括)到 toIndex
(不包括)。
int[] array = {1, 2, 3, 4, 5};
random.shuffle(array, 1, 4); // 从索引 1 开始到索引 3(不包括)的元素进行随机排序
这些方法为开发人员提供了生成各种类型随机数的功能,以满足不同的需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。