How to generate a random alpha-numeric string

前端 未结 30 2462
忘掉有多难
忘掉有多难 2020-11-21 05:38

I\'ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifie

30条回答
  •  独厮守ぢ
    2020-11-21 06:13

    I think this is the smallest solution here, or nearly one of the smallest:

     public String generateRandomString(int length) {
        String randomString = "";
    
        final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();
        final Random random = new Random();
        for (int i = 0; i < length; i++) {
            randomString = randomString + chars[random.nextInt(chars.length)];
        }
    
        return randomString;
    }
    

    The code works just fine. If you are using this method, I recommend you to use more than 10 characters. A collision happens at 5 characters / 30362 iterations. This took 9 seconds.

提交回复
热议问题