This commit is contained in:
2023-03-04 16:29:55 +08:00
commit 397ba75479
1007 changed files with 109050 additions and 0 deletions

View File

@@ -0,0 +1,84 @@
package com.jsowell.common.util;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* 获取随机数的工具类
*/
public class RandomUtil {
private static final String SYMBOLS_NUM = "0123456789"; // 纯数字
//如果需加入字母就改成0123456789abcdefg...........
private static final String SYMBOLS_NUM_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
private static final Random RANDOM = new SecureRandom();
/**
* 获取6位的短信验证码 纯数字
*
* @return 随机数字
*/
public static String getSMSVerificationCode() {
return getRandomNumber(6);
}
/**
* 获取指定长度随机数
*
* @param length 需要的长度
* @return 随机数
*/
public static String getRandomNumber(int length) {
char[] nonceChars = new char[length]; //指定长度,自己可以设置
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS_NUM.charAt(RANDOM.nextInt(SYMBOLS_NUM.length()));
}
return new String(nonceChars);
}
/**
* 获取一组不重复的6位数随机数
*
* @param num 数量
* @return
*/
public static List<String> getRandomNumberList(int num) {
List<String> list = Lists.newArrayList();
for (int i = 0; i < num; i++) {
String code = getNotRepeatCode(list);
// System.out.println(code);
list.add(code);
}
return list;
}
/**
* 获取一组不重复的6位数随机数
*/
private static String getNotRepeatCode(List<String> list) {
// 获取随机验证码
String code = RandomUtil.getSMSVerificationCode();
// 判断list中是否存在
boolean contains = list.contains(code);
if (contains) {
// 已经存在,重新获取一个
code = getNotRepeatCode(list);
}
return code;
}
public static void main(String[] args) {
List<String> randomNumberList = getRandomNumberList(100000);
Set<String> set = Sets.newHashSet(randomNumberList);
System.out.println("list长度" + randomNumberList.size());
System.out.println("set长度" + set.size());
}
}