随机数
public class RandomUtil {
/**
* 获取随机位数的(数字)字符串
* @param length 位数
* @return
*/
public static String getRandomNumber(int length) {
String base = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 获取随机位数的字符串
* @param length 位数
* @return
*/
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 获取随机数
* @param total 总数
* @param length 返回位数
* @return
*/
public static List<Integer> getRandomNumber(Integer total,int length,List<Integer> list) {
if(ToolUtil.isEmpty(list)){
list = new ArrayList<>();
}
Random random = new Random();
for (int i = 0; i < length; i++) {
list.add(RandomUtil.getRandomValue(list,total,random));
}
return list;
}
/**
* 返回随机数,不可重复
* @param list
* @param total
* @return
*/
public static Integer getRandomValue(List<Integer> list,Integer total,Random random){
if(ToolUtil.isOneEmpty(total,random)){
return null;
}
if(ToolUtil.isEmpty(list)){
list = new ArrayList<>();
}
Integer number = random.nextInt(total) + 1;
if(list.contains(number)){
return RandomUtil.getRandomValue(list,total,random);
}else {
return number;
}
}
}