日期:2014-05-20  浏览次数:20765 次

java产生随机数
思路:java产生一个随机8位数,跟数据库某个字段作对比,
如果随机数存在,则重新随机,直到是唯一的。
如何实现起来效率比较高?

各位如果有其他方法也可以提出。。。求代码实现。

------解决方案--------------------
用时间吧,
Java code

Date date = new Date();
SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
String number = df1.format(date);//这里String取出的就是唯一的随机数,

//截取8位和比较你自己解决。时间函数产生效率高,而且一般系统都需要时间列,一举两得、减少冗余

------解决方案--------------------
public String randomABC(int length) {// 随机字母
Random random = new Random();
String val = "";
for (int i = 0; i < length; i++) {
int choice = random.nextInt(2) % 2 == 0 ? 97 : 97; // 取得65大写还是97小写
val += (char) (choice + random.nextInt(26));
}
return val;
}

public String random123(int length) {// 随机数字
Random random = new Random();
String val = "";
for (int i = 0; i < length; i++) {

val += random.nextInt(10) + "";
}
return val;
}
参数就是你要生成多少位的
------解决方案--------------------
Java code

Date date = new Date();
SimpleDateFormat df1 = new SimpleDateFormat("ddHHmmss");
String number = df1.format(date);//这里String取出的就是唯一的随机数,