import java.util.HashSet;
import java.util.Set;
/**
* <p>
*? ? 獲取不重復(fù)隨機(jī)數(shù)
* </p>
*
* @author passer
* @since 2021-03-09
*/
public class RandomUtil {
? ? private static final Set set = new HashSet();
? ? private static Integer min;//隨機(jī)數(shù)最小值
? ? private static Integer max;//隨機(jī)數(shù)最大值
? ? /**
? ? *
? ? * @param min 隨機(jī)數(shù)最小值
? ? * @param max 隨機(jī)數(shù)最大值(不包含)
? ? */
? ? public RandomUtil(Integer min, Integer max){
? ? ? ? this.min = min;
? ? ? ? this.max = max;
? ? }
? ? /**
? ? *
? ? * @return 隨機(jī)數(shù)
? ? */
? ? 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();
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
————————————————
最后经瓷,分享一個博客:一路有你