我使用它在方法内生成随机数并返回它:
int randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
如何确保不存在连续的两个随机数?我不在乎我是否得到 3,然后是 5,然后再次得到 3。仅当我得到 3,然后得到 3 时。
最佳答案
int temp = -1; // This will be your value to be compared to random value
for(int i = 0; i < 10; i++) { // assuming your filteredArraylist is size 10
int randomValue = ThreadLocalRandom.current().nextInt(0, 10);
if(randomValue == temp) {
i--; // it will repeat the generation of random value if temp and randomValue is same
} else {
temp = randomValue; // you will put here the ne random value to be compared to next value
System.out.println(randomValue);
}
关于java - Java中如何生成不重复的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44814374/