3

I'm trying to generate a unique id for each request in a DS. I'm thinking of concatenating a random integer and timestamp of the request's receipt. Since, getting a random integer can result in negative values I decided to print hex representation:

     String randomPrefix = Integer.toHexString(RANDOM.nextInt()).toUpperCase();
     java.util.Date date = new java.util.Date();
     String timestamp = Long.toHexString(date.getTime()).toUpperCase();
     String id = randomPrefix.concat(timestamp);    

I'm nt very good at probabilities, but I want to know if there are other operations which could result in equally low (or even better chances of not seeing repetition) in this value with shorter string lengths.

Speaking like a layman, concatenation should X the chances of recurrence whereas addition would + it (which has higher chances of being repeated).

Please suggest other ways to result in a cleaner and shorter ID (or confirm if this is correct).

P.S: Please forgive me for the layman language, working on it. :(

user1071840
  • 3,522
  • 9
  • 48
  • 74
  • 1
    If you need truly unique ids, use UUID as suggested by @NKukhar. If you need a unique id while the program is running, you can just increment an AtomicInteger. – agbinfo Jul 29 '13 at 22:44

1 Answers1

5

Try to use UUID

System.out.println(UUID.randomUUID().toString());

Prints something like:

3aae7d1a-8799-4a6f-8863-cde6b1782e7b

It's a common practice to use if for ids

But why do you need short random id? You should understand that with short id there are more chance to get duplicates, and ID usually field for programs and not for people.

nkukhar
  • 1,975
  • 2
  • 18
  • 37