199

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

任何指导表示赞赏,谢谢。

我应该提到我正在使用 Java 5。

4

11 回答 11

407

创建一个UUID

String uniqueID = UUID.randomUUID().toString();
于 2009-09-07T14:51:01.363 回答
55

如果您想要简短的、人类可读的 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());
}
于 2009-09-07T14:53:52.060 回答
23

java.util.UUID : toString() 方法

于 2009-09-07T14:50:09.193 回答
19

这是我的两分钱:我之前实现了一个类,它以[host name]-[application start time]-[current time]-[discriminator]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());
    }
  }
}
于 2009-09-07T15:15:51.057 回答
11

使用 Java 生成唯一 ID

UUID 是在 Java 中生成唯一 ID 的最快和最简单的方法。

import java.util.UUID;

public class UniqueIDTest {
  public static void main(String[] args) {
    UUID uniqueKey = UUID.randomUUID();
    System.out.println (uniqueKey);
  }
}
于 2012-10-25T06:44:14.300 回答
8

恕我直言,aperkins提供了一个优雅的解决方案,因为它是原生的并且使用更少的代码。但是如果您需要更短的 ID,您可以使用这种方法来减少生成的字符串长度:

// usage: GenerateShortUUID.next();
import java.util.UUID;

public class GenerateShortUUID() {

  private GenerateShortUUID() { } // singleton

  public static String next() {
     UUID u = UUID.randomUUID();
     return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits());
  }

  private static String toIDString(long i) {
      char[] buf = new char[32];
      int z = 64; // 1 << 6;
      int cp = 32;
      long b = z - 1;
      do {
          buf[--cp] = DIGITS66[(int)(i & b)];
          i >>>= 6;
      } while (i != 0);
      return new String(buf, cp, (32-cp));
  }

 // array de 64+2 digitos 
 private final static char[] DIGITS66 = {
    '0','1','2','3','4','5','6','7','8','9',        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    '-','.','_','~'
  };

}
于 2013-06-03T22:36:01.737 回答
7

这为 UUID 生成增加了一点随机性,但确保每个生成的 id 长度相同

import org.apache.commons.codec.digest.DigestUtils;
import java.util.UUID;

public String createSalt() {
    String ts = String.valueOf(System.currentTimeMillis());
    String rand = UUID.randomUUID().toString();
    return DigestUtils.sha1Hex(ts + rand);
}
于 2016-07-06T03:06:52.527 回答
4

UUID我们可以通过使用和调用类似randomUUID()on的方法在 java 中创建一个唯一 ID UUID

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

这将生成uniqueID返回类型为的随机数String

于 2015-08-27T09:30:08.477 回答
2

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

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

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

2) SecureRandom 和 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);
于 2017-10-10T19:47:55.353 回答
1

带有计数信息的唯一 ID

import java.util.concurrent.atomic.AtomicLong;

public class RandomIdUtils {

    private static AtomicLong atomicCounter = new AtomicLong();

    public static String createId() {

        String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
        String uniqueId = UUID.randomUUID().toString();

        return uniqueId + "-" + currentCounter;
    }
}
于 2017-11-22T15:54:02.887 回答
1
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;
}
于 2017-12-26T19:50:33.430 回答