如何生成无法在 java 中重复使用的随机 ID 号?

  • 本文关键字:随机 ID 何生成 java java
  • 更新时间 :
  • 英文 :


对于我当前的java项目,我正在尝试为注册用户生成随机ID's。到目前为止,我一直使用min +(int) (Math.random()*((max-min)+1))作为我的公式来生成随机数。我面临的问题是,有时数字会重复,我的应用程序无法使用它们。

int min = 1001;
int max = 1050;

for (int i=1; i<=1; i++)
{
int a = min +(int) (Math.random()*((max-min)+1));


}



我尝试过使用和合并

Integer[] arr = new Integer[100];
for (int i = 1; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));

但是所生成的数字将不断地显示为"0";空";它会重复几百次循环并淹没我的txt文件。

通常,随机生成器RandomMath.random()不是生成唯一id的正确方法。正如您所提到的,它可能会重复(而且肯定会重复(。

我推荐两种生成ID的方法。

第一种是使用AtomicInteger。当您的ID应该是唯一不是随机时,这很好。

private static final AtomicInteger ID = new AtomicInteger(0);
public static String generateUniqueId() {
return String.valueOf(ID.incrementAndGet());
}

第二个对我来说更可取的方法是使用UUID。当您的ID应该是唯一随机时,这很好。

public static String generateUniqueId() {
return String.valueOf(UUID.randomUUID());
}

我可以提到的另一个是使用System.nanoTime()

public static String generateUniqueId() {
return String.valueOf(System.nanoTime());
}

很久以前,我进行了一些调查,发现对于正常的有效载荷来说,这是相当稳定的。但一般来说,如果您构建这样一个系统,它可以检索到相同的值,该系统应该经常生成ID

我建议生成UUID,而不是生成数字。发生碰撞的可能性几乎是不可能的。

UUID id = UUID.randomUUID();

否则,如果你想坚持数字,我建议你在应用程序中实现一些序列服务。

import java.util.concurrent.atomic.AtomicLong;
public class SequenceService {
private final AtomicLong ids;
public SequenceService() {
long initialValue = getInitialValue();
this.ids = new AtomicLong(initialValue);
}
public long generateNextId() {
return ids.incrementAndGet();
}
private long getInitialValue() {
// this methods reads the last known leased id (e.g. from the file system)
}
}

最新更新