获取不重复随机数,自定义取值范围
import java.util.HashSet;
import java.util.Set;
/**
* <p>
* 获取不重复随机数
* </p>
*
* @author passer
* @since 2021-03-09
*/
public class RandomUtil {
private static final Set set = new HashSet();
private static Integer min;//随机数最小值
private static Integer max;//随机数最大值
/**
*
* @param min 随机数最小值
* @param max 随机数最大值(不包含)
*/
public RandomUtil(Integer min, Integer max){
this.min = min;
this.max = max;
}
/**
*
* @return 随机数
*/
public String getRandom(){
Integer num = new java.util.Random().nextInt(max - min) + min;
boolean b = true;
while (b){
if(set.contains(num)){
num = new java.util.Random().nextInt(max - min) + min;
}else {
set.add(num);
return "" + num;
}
if(set.size() == max-min){
b = false;
num = null;
return "" + num;
}
}
return "" + num;
}
public void clearSet(){
set.clear();
}
public static void main(String[] args) {
RandomUtil randomUtil = new RandomUtil(100,1000);//声明一次
for(int i = 0; i < 1000; i++){
System.out.println(randomUtil.getRandom());
if(i>900){
randomUtil.clearSet();
}
}
}
}