java语言基础的问题! 我是初学者,就是想问一下怎么样才能让随机数不重复

2025-01-02 05:57:12
推荐回答(1个)
回答1:

你可以定义一个Map来存储已经生成的字符,后面生成随机数的时候,你就map.containsKey("xx")判断下那个字符串是否存在,入股存在,就重新生成;
Java代码如下:
public static char[] generate() {
char[] chs = new char[5];
char[] letters = {'A','B','C','D','E','F','G',
'H','I','J','K','L','M','N',
'O','P','Q','R','S','T',
'U','V','W','X','Y','Z'
};
Map map = new HashMap(); //新定义
for(int i = 0; i < chs.length; i++) {
int index = (int)(Math.random()*letters.length);
while(map.containsKey(letters[index]+"")){
index = (int)(Math.random()*letters.length);
}
map[letters[index]+""] = true;
chs[i] = letters[index];
}
map = null;
}