How to generate a random alpha-numeric string

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

    Surprising, no one here has suggested it, but:

    import java.util.UUID
    
    UUID.randomUUID().toString();
    

    Easy.

    The benefit of this is UUIDs are nice, long, and guaranteed to be almost impossible to collide.

    Wikipedia has a good explanation of it:

    " ...only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%."

    The first four bits are the version type and two for the variant, so you get 122 bits of random. So if you want to, you can truncate from the end to reduce the size of the UUID. It's not recommended, but you still have loads of randomness, enough for your 500k records easy.

提交回复
热议问题