Categories
Computing Java

Generating Short Alphanumeric Identifiers in Java

I will make it short and sweet, for a change: suppose you have a large number that you want to distribute to users, and you want to instead to give them a shorter, easier to share string of characters.  220p9 instead of 3453453. Neat, no?

I grappled with this, being a moron, for way too long – looking into Apache Commons Id. The issue is that I also needed to use this ID with a database, and that means that there could be issues of concurrent requests for identifiers and other messy situations. I also did not need something overly fancy, just alphanumeric identifiers. The problem was that I was too stressed to think, if I may be excused. Anyway, the solution is just silly:

Let the database generate the usual integer unique identifiers that grow with time. Whenever you need to use a short, alphanumeric identifier, simply use base conversion, to base 36, on that number. How easy is that? The conversion, in Java is done using the Long or Integer objects’ toString(number, radix) methods. To convert back use the valueOf() method.

Pretty bad of me.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Share