我正在寻找在Java中创建唯一ID作为字符串的最佳方法。

任何指导都很感激,谢谢。

我应该提到我使用的是Java 5。


当前回答

在java中有三种生成唯一id的方法。

1) UUID类提供了一种生成唯一id的简单方法。

 UUID id = UUID.randomUUID();
 System.out.println(id);

2) securerrandom和MessageDigest

//initialization of the application
 SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");

//generate a random number
 String randomNum = new Integer(prng.nextInt()).toString();

//get its digest
 MessageDigest sha = MessageDigest.getInstance("SHA-1");
 byte[] result =  sha.digest(randomNum.getBytes());

System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + new String(result));

3)使用java.rmi.server.UID

UID userId = new UID();
System.out.println("userId: " + userId);

其他回答

我们可以使用UUID在java中创建一个唯一的ID,并调用UUID上的randomUUID()方法。

String uniqueID = UUID.randomUUID().toString();

这将生成一个随机的uniqueID,其返回类型为String。

以下是我的两美分价值:我之前实现了一个IdFactory类,它创建的id格式为[主机名]-[应用程序启动时间]-[当前时间]-[鉴别器]。这在很大程度上保证了id在JVM实例中是唯一的,同时保持id可读(尽管相当长)。以下是代码,以防它有任何用处:

public class IdFactoryImpl implements IdFactory {
  private final String hostName;
  private final long creationTimeMillis;
  private long lastTimeMillis;
  private long discriminator;

  public IdFactoryImpl() throws UnknownHostException {
    this.hostName = InetAddress.getLocalHost().getHostAddress();
    this.creationTimeMillis = System.currentTimeMillis();
    this.lastTimeMillis = creationTimeMillis;
  }

  public synchronized Serializable createId() {
    String id;
    long now = System.currentTimeMillis();

    if (now == lastTimeMillis) {
      ++discriminator;
    } else {
      discriminator = 0;
    }

    // creationTimeMillis used to prevent multiple instances of the JVM
    // running on the same host returning clashing IDs.
    // The only way a clash could occur is if the applications started at
    // exactly the same time.
    id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
    lastTimeMillis = now;

    return id;
  }

  public static void main(String[] args) throws UnknownHostException {
    IdFactory fact = new IdFactoryImpl();

    for (int i=0; i<1000; ++i) {
      System.err.println(fact.createId());
    }
  }
}
String name,password;

public int idGen() {

    int id = this.name.hashCode() + this.password.hashCode();
    int length = String.valueOf(id).length();
    int Max_Length = 5;
    if(String.valueOf(id).length()>Max_Length) 
    {
        id = (int) (id /Math.pow(10.0,length - Max_Length ));
    }
    return  id;
}

如果你想要简短的、人类可读的id,并且只需要它们在每次JVM运行时是唯一的:

private static long idCounter = 0;

public static synchronized String createID()
{
    return String.valueOf(idCounter++);
}    

编辑:评论中建议的替代方案-这依赖于底层的线程安全“魔法”,但更可扩展,同样安全:

private static AtomicLong idCounter = new AtomicLong();

public static String createID()
{
    return String.valueOf(idCounter.getAndIncrement());
}

创建UUID。

String uniqueID = UUID.randomUUID().toString();