RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Web
Expertise: Intermediate
Jun 14, 2017

Creating the Hash for Short URLs

The hashing function is used to generate random strings of six characters, that can be numbers or upper and lowercase letters. We need to make sure that a string is not already used, but, choosing from 62 characters, we can make about ten billions strings. If we are getting repeated strings, we will output some warnings, and in this case, the solution would be to use longer codes or just start reusing them.

In the sample of code below, we generate the short code of six characters:

public class HystqioUtils {
             private static final String CHARSET = 
             public static String generateShortCode() {
                  StringBuilder buffer = new StringBuilder();
                  for (int i-0; i                        int r = random.nextInt(CHARSET.length());
             return buffer.toString();
Octavia Anghel
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date