Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a unique identifier of a fixed length in Java?

I am trying to generate a unique identifier of a fixed length such as the IDs that are generated by Megaupload for the uploaded files.

For example:

  • ALGYTAB5
  • BCLD23A6

In this example using from A-Z and 0-9 and with a fixed length of 8 the total different combinations are 2,821,109,907,456.

What if one of the generated id is already taken. Those ids are going to be stored in a database and it shouldn't be used more than once.

How can I achieve that in Java?

Thank you.

like image 506
Alfredo Osorio Avatar asked Jul 05 '11 14:07

Alfredo Osorio


2 Answers

Hmm... You could imitate a smaller GUID the following way. Let first 4 bytes of your string be the encoded current time - seconds passed after Unix. And the last 4 just a random combination. In this case the only way two ID's would coincide is that they were built at the same second. And the chances of that would be very veeery low because of the other 4 random characters.

Pseudocode:

get current time (4 byte integer
id[0] = 1st byte of current time (encoded to be a digit or a letter)
id[1] = 2nd
id[2] = 3rd
id[3] = 4th
id[4] = random character
id[5] = random character
id[6] = random character
id[7] = random character
like image 89
Armen Tsirunyan Avatar answered Sep 17 '22 16:09

Armen Tsirunyan


I have tried @Armen's solution however I would like to give another solution

    UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
UUID idThree = UUID.randomUUID();
UUID idFour = UUID.randomUUID();

String time = idOne.toString().replace("-", "");
String time2 = idTwo.toString().replace("-", "");
String time3 = idThree.toString().replace("-", "");
String time4 = idFour.toString().replace("-", "");

StringBuffer data = new StringBuffer();
data.append(time);
data.append(time2);
data.append(time3);
data.append(time4);

    SecureRandom random = new SecureRandom();
int beginIndex = random.nextInt(100);       //Begin index + length of your string < data length
int endIndex = beginIndex + 10;            //Length of string which you want

String yourID = data.substring(beginIndex, endIndex);

Hope this help!

like image 31
Lunf Avatar answered Sep 17 '22 16:09

Lunf