6位数字理论上应该是100W变换,超过100w肯定是重复的
我们方法主要是用到了迭代和集合
直接上代码吧:
方法:
/**
* 获取数组不存在的6位数取件码
* @return
*/
private String getPickupCode(List<String> list){
String sixstr = RandomUtil.getSixstr();
boolean contains = list.contains(sixstr);
if (contains || sixstr.length()!=6){
sixstr =getPickupCode(list);
}
return sixstr;
}
数字生成类:
import java.security.SecureRandom;
import java.util.Random;
public class RandomUtil {
private static final String SYMBOLS = "0123456789"; // 纯数字
//如果需加入字母就改成0123456789abcdefg...........
private static final Random RANDOM = new SecureRandom();
public static void main(String[] args) {
System.out.println(getSixstr());
}
/**
* 获取长度为 6 的随机数字
* @return 随机数字
*/
public static String getSixstr() {
char[] nonceChars = new char[6]; //指定长度,自己可以设置
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
}
测试:
public static void main(String[] args) {
List<String> list=new ArrayList<>();
//随机生成10万个6位不重复随机数
for (int i = 0; i <100000 ; i++) {
String pickupCode = getPickupCode(list);
list.add(pickupCode);
System.out.println(list.get(i));
}
//检查一下是否重复
Map<String,String> map=new HashMap<>();
for (String s:list) {
map.put(s,s);
}
System.out.println("list集合大小:"+list.size());
System.out.println("map集合大小:"+map.size());
if (list.size()==map.size()){
System.out.println("没有重复值");
}else {
System.out.println("有重复值");
}
}
结果: