如何在Java中创建唯一ID? [重复]

问题描述 投票:149回答:12

这个问题在这里已有答案:

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

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

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

java uniqueidentifier
12个回答
307
投票

创建一个UUID

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

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

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

-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

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

22
投票

java.util.UUID:toString()方法


18
投票

这是我的两分钱:我之前已经实现了一个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());
    }
  }
}

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

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
投票

恕我直言aperkins提供了一个优雅的解决方案原因是本机和使用较少的代码。但是如果你需要一个较短的ID,你可以使用这种方法来减少生成的String长度:

// 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',
    '-','.','_','~'
  };

}

2
投票

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

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

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


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);
© www.soinside.com 2019 - 2024. All rights reserved.