Generate key to access document

Asked

Viewed 37 times

0

I need to generate a key that contains letters and numbers Ex: "AJ67G8". I am generating with Random from java.io.Serializable:

public static String nomeAleatorio(int nCaracteres) {
    Random rand = new Random();
    char[] letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

    StringBuffer sb = new StringBuffer();

    for (int i = 0; i <= nCaracteres; i++) {
        int ch = rand.nextInt(letras.length);
        sb.append(letras[ch]);
    }
    return sb.toString();
}

This key has to be unique, the problem is that Ramdom doesn’t guarantee it and keep going to the bank every time to check if the key exists is too much work. What strategy to use to solve this problem?

  • https://answall.com/search?q=+fisher-yates

1 answer

1


The easiest way to solve this would be with UUID (Universal Unique Identifier) which is represented by 128-bit value.

You can generate one with the following code snippet:

private String geraChaveUnica()
{
    final String idUnico = UUID.randomUUID().toString().replace("-", "");
    return idUnico;
}

Output:

feefa833f1184bd3bfa44272bea74a75

Browser other questions tagged

You are not signed in. Login or sign up in order to post.