Generating Alphanumeric random string in Java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

   This question already has an answer here:
    * /questions/41107/how-to-generate-a-random-alpha-numeric-string /questions/41107/how-to-generate-a-random-alpha-numeric-string 38 answers

Answers

If you want to control the characterset and length take for example

public static String randomString(char[] characterSet, int length) {
    Random random = new SecureRandom();
    char[] result = new char[length];
    for (int i = 0; i < result.length; i++) {
        // picks a random index out of character set > random character
        int randomCharIndex = random.nextInt(characterSet.length);
        result[i] = characterSet[randomCharIndex];
    }
    return new String(result);
}

and combine with

char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

to specify the characterset.

It s not based on StringBuilder since you know the length and don t need all the overhead.

It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.

http://ideone.com/xvIZcd http://ideone.com/xvIZcd

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/18069434/generating-alphanumeric-random-string-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils