Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

8 chars unique String in Java

Is there any way to generate 8 characters long random and unique String in Java?

String id = getRandomString();

and then id will be for example wf41Av5g

like image 522
danny.lesnik Avatar asked Oct 17 '11 08:10

danny.lesnik


2 Answers

The uniqueness property depends on the scope in which you use it. Java can certainly generate random strings, although if you want a universally unique identifier you can use UUID class.

String unique = UUID.randomUUID().toString();
like image 115
Johan Sjöberg Avatar answered Oct 19 '22 22:10

Johan Sjöberg


If the uniqueness is important, you can't simply randomly generate strings. There is no way to avoid a collision. Even UUIDs can collide, although it is quite unlikely.

You could keep a record of the strings you've used, and when you generate a new random string, check the record to see if it's a duplicate, and if so, discard it and try again.

However, what i would suggest is that you don't generate random numbers. Instead, keep a counter, and encrypt its output to produce random-looking numbers. These are guaranteed never to collide if you do this properly. See an earlier answer of mine, or one by Rossum

like image 43
Tom Anderson Avatar answered Oct 20 '22 00:10

Tom Anderson