Search code examples
javauniqueidentifieridentifier

Any Java way of generating an identifying string that is similar to YouTube's video string?


Each video at YouTube has a unique identifying string such as 1cru2fzUlEc.

Is any Java way of generating something close to it? By close I mean the string is unique, short, and uses numbers and letters (case-sensitive).

I need to use such a string in the same way YouTube uses: identify a record in the backend system. I am doing a Java web application. I don't want to use the approach of http://example.com?id=123.

I know Java's UUID implementation can produce similar results, but it is too long compared to what YouTube has.

Thanks!

Edit 1:

Thanks so much to you all for your replies. All your input is USEFUL! It appears that there is no perfect solution. Anything perfect (if not UUID) must generate and check (to avoid duplicates). Am I right?

Can I safely say that YouTube faces the same issues when generating its own 12-character video string as we Java people do?

Cheers!

Edit 2:

I would like to use full range of alphanumeric characters and not just hexadecimal digits. I am going to use the solution from Marcus Junius Brutus. I feel it is intuitive and safely enough. Theoretically I will have to check each generated string, but I am not going to, because each check is another database call. I am going to add unique constraint to the table field for the generated string ID. I am going to let that unlucky user to fail maybe the first time he generates a record. What he needs to do is to go back to the form fill it again and save it (hopefully not fail second time due to repeated string values). Initially I am going to use 12-char string and I can increase the length easily when there is a need.

I am going to use this solution for a distributed web application talking to the same backend database, which means multiple JVMs for the same application.

Here is my solution and I hope it will work.

    String sampleAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    char[] buf = new char[12];
    for (int i = 0 ; i < 12 ; i++)
        buf[i] = sampleAlphabet.charAt(random.nextInt(sampleAlphabet.length()));
    return new String(buf);

Thank you all for your responses. They are all acceptable solutions.I really appreciate it.

Best to you all!


Solution

  • Why don't you try this? It satisfies all your needs.

    https://github.com/peet/hashids.java