Skip to main content

Posts

Showing posts from October, 2009

How to genarate Unique ID in Java

Style 1 - UUID

import java.util.UUID;

public class GenerateUUID {

public static final void main(String... aArgs){
//generate random UUIDs
UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
log("UUID One: " + idOne);
log("UUID Two: " + idTwo);
}

private static void log(Object aObject){
System.out.println( String.valueOf(aObject) );
}
}



Example run :

>java -cp . GenerateUUID
UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00
UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889

If Java 5 is not available, then there are other more laborious ways to generate unique ids


Style 2 - SecureRandom and MessageDigest

import java.security.SecureRandom;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GenerateId {

public static void main (String... arguments) {
try {
//Initialize SecureRandom
//This is a lengthy operation, to be done only upon
//initialization of the application
SecureRandom …