可能重复:
在 Java 中生成 UUID
我需要生成一个 9 位数的唯一代码,就像产品背面使用的代码一样,以识别它们。
代码应该是不重复的,并且它们应该在数字之间没有相关性。而且代码应该都是整数。
我需要使用 java 生成它们并同时将它们插入数据库。
可能重复:
在 Java 中生成 UUID
我需要生成一个 9 位数的唯一代码,就像产品背面使用的代码一样,以识别它们。
代码应该是不重复的,并且它们应该在数字之间没有相关性。而且代码应该都是整数。
我需要使用 java 生成它们并同时将它们插入数据库。
生成一个 9 位随机数并在数据库中查找它的唯一性。
100000000 + random.nextInt(900000000)
或者
String.format("%09d", random.nextInt(1000000000))
使用 Commons Lang 的randomNumeric
方法:
不过,您必须检查数据库的唯一性。
int noToCreate = 1_000; // the number of numbers you need
Set<Integer> randomNumbers = new HashSet<>(noToCreate);
while (randomNumbers.size() < noToCreate) {
// number is only added if it does not exist
randomNumbers.add(ThreadLocalRandom.current().nextInt(100_000_000, 1_000_000_000));
}
我知道这样做有点奇怪,但我仍然认为你可以拥有唯一的 9 位数字,彼此之间几乎没有关系......
问你问there should have no correlation between the numbers
public class NumberGen {
public static void main(String[] args) {
long timeSeed = System.nanoTime(); // to get the current date time value
double randSeed = Math.random() * 1000; // random number generation
long midSeed = (long) (timeSeed * randSeed); // mixing up the time and
// rand number.
// variable timeSeed
// will be unique
// variable rand will
// ensure no relation
// between the numbers
String s = midSeed + "";
String subStr = s.substring(0, 9);
int finalSeed = Integer.parseInt(subStr); // integer value
System.out.println(finalSeed);
}
}