How to generate a random alpha-numeric string

前端 未结 30 2567
忘掉有多难
忘掉有多难 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:10

    You can use the UUID class with its getLeastSignificantBits() message to get 64 bit of random data, and then convert it to a radix 36 number (i.e. a string consisting of 0-9,A-Z):

    Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
    

    This yields a string up to 13 characters long. We use Math.abs() to make sure there isn't a minus sign sneaking in.

提交回复
热议问题