Creating the Hash for Short URLs

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 =                 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";             public static String generateShortCode() {                  StringBuilder buffer = new StringBuilder();                  for (int i-0; i                        int r = random.nextInt(CHARSET.length());                       buffer.append(CHARSET.charAt(r));                       }             return buffer.toString();             }          }

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist