我想使用java创建唯一数量的“Long”类型。我见过几个例子,但他们使用时间戳,不使用时间戳我可以创建唯一数量的包装对象“Long”。请建议。
请建议。谢谢。
最佳答案
通过调用 random.nextInt 生成每个数字。为了唯一性,您可以通过将它们保存在一个集合中并检查该集合是否包含您每次生成的数字来跟踪迄今为止使用的随机数。
public static long generateRandom(int length) {
Random random = new Random();
char[] digits = new char[length];
digits[0] = (char) (random.nextInt(9) + '1');
for (int i = 1; i < length; i++) {
digits[i] = (char) (random.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
关于java - 生成唯一数量的包装对象 Long 类型的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24531366/