生成不重复的随机数

要求:此随机数中只允许出现0-9的数字,a-z和A-Z

View Code
 1 package com.study.pratice03;
2
3 import java.security.SecureRandom;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 class RandomString
8 {
9 private static final String POSSIBLE_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
10
11 public String getRandomString(int length)
12 {
13 StringBuffer sbf=new StringBuffer();
14 SecureRandom random = new SecureRandom();
15 for (int i = 0; i < length; i++)
16 {
17 sbf.append(POSSIBLE_CHARS.charAt(random.nextInt(POSSIBLE_CHARS
18 .length())));
19 }
20 return sbf.toString();
21 }
22 }
23 public class RandomStringTest
24 {
25 public static void main(String[] args)
26 {
27 // TODO Auto-generated method stub
28 System.out.println(new RandomString().getRandomString(10));
29 //测试
30 /*for (int i = 0; i < 2000000; i++)
31 {
32 String s = new RandomString().getRandomString(10);
33 Set<String> check = new HashSet<String>();
34 if (check.contains(s))
35 {
36 throw new IllegalStateException("重复字符被发现: " + s);
37 }
38 else
39 {
40 System.out.println("产生第"+(i+1)+"个字符:"+s);
41 check.add(s);
42 }
43 }*/
44 }
45
46 }



原文地址:https://www.cnblogs.com/xiongyu/p/2281079.html