如何在 Java 中生成不会重复的随机值
要生成不会重复的随机值,请使用 HashSet 集合。首先,创建一个随机对象和 HashSet -
Random randNum = new Random(); Set<Integer>s = new HashSet<Integer>();
现在,添加随机整数 -
while (s.size() < 10) { s.add(randNum.nextInt()); }
现在,显示唯一随机数 -
List<Integer>list = new ArrayList<Integer>(s); System.out.println(list);
示例
import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.Random; import java.util.List; public class Demo { public static void main(String[] args) { Random randNum = new Random(); Set<Integer>s = new HashSet<Integer>(); while (s.size() < 10) { s.add(randNum.nextInt()); } System.out.println("Random numbers that aren't repeating..."); List<Integer>list = new ArrayList<Integer>(s); System.out.println(list); } }
输出
Random numbers that aren't repeating... [-951684393, -2119833673, 1804429247, -1389537752, -1314261216, 575783898, 326063891, -1241554605, -613888875, -1698001241]
让我们看另一个示例,获取不会重复的不同随机数 -
Random numbers that aren't repeating... [1173054490, -613376175, -1947139369, -840397233, 931136232, 135129829, 1634496580, 13228721, 1929509800, 1205305181]
广告