如何在Java中创建唯一ID?

时间:2009-09-07 14:48:32

标签: java uniqueidentifier

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

感谢任何指导,谢谢。

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

12 个答案:

答案 0 :(得分:307)

创建UUID

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

答案 1 :(得分:45)

如果您需要简短的,人类可读的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());
}

答案 2 :(得分:22)

java.util.UUID:toString()方法

答案 3 :(得分:18)

这是我的两分钱:我之前已经实现了一个IdFactory类,它以 [主机名] - [应用程序开始时间] - [当前时间] - [鉴别器] <格式创建ID / em>的。这在很大程度上保证了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());
    }
  }
}

答案 4 :(得分:9)

这为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);
}

答案 5 :(得分:6)

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);
  }
}

答案 6 :(得分:6)

恕我直言 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',
    '-','.','_','~'
  };

}

答案 7 :(得分:2)

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

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

这将生成随机uniqueID,其返回类型为String

答案 8 :(得分:0)

在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);

答案 9 :(得分:0)

包含计数信息的唯一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;
    }
}

答案 10 :(得分:0)

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;
}

答案 11 :(得分:-5)

enter code here

Program for generating unique IDs

class Test {

    public static void main(String arg[]) {

        String s = "";
        double d;
        for (int i = 1; i <= 16; i++) {
            d = Math.random() * 10;
            s = s + ((int)d);
            if (i % 4 == 0 && i != 16) {
                s = s + "-";
            }
        }

        System.out.println(s);
    }
}

Output:

7954-7605-1827-4795
1991-4912-4912-3008