开发者

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开发者_StackOverflow 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.


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


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!


We're using the database to check whether they already exist. If the number of IDs is low compared to the possible number you should be relatively safe.

You might also have a look at the UUID class (although it's 16-byte UUIDs).


Sounds like a job for a hash function. You're not 100% guaranteed that a hash function will return a unique identifier, but it works most of the time. Hash collisions must be dealt with separately, but there are many standard techniques for you to look into.

Specifically how you deal with collisions depends on what you're using this unique identifier for. If it's a simple one-way identifier where you give your program the ID and it returns the data, then you can simply use the next available ID in the case of a collision.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜