我只想获取一个公司名称,并且只想获取一次。因此,如果已经获取了它,则不应再次获取它。
代码如下:
private static String[] billercompanies = {
"1st",
"TELUS Communications",
"Rogers Cablesystems",
"Shaw Cable",
"TELUS Mobility Inc",
"Nanaimo Regional District of",
"Credit Union MasterCard",
};
public static String GetBillerCompany(){
String randomBillerComp = "";
randomBillerComp = (billercompanies[new Random().nextInt(billercompanies.length)]);
return randomBillerComp;
}
最佳答案
只需使用 Collections 打乱您想要的数组即可
Collections.shuffle(List);
因此只需从数组创建一个列表
List<E> list = Arrays.asList(array);
然后用上面的方法打乱
Collections.shuffle(list);
您的列表可以从左到右阅读,因为它是随机的。 所以只需保存索引即可
int currentIndex = 0;
public E getRandom(){
//If at the end, start over
if(++currentIndex == list.size()) {
currentIndex = 0;
shuffle(list);
}
return list.get(currentIndex);
}
每次您想忘记已使用的重复列表时,只需再次打乱数组即可
Collections.shuffle(list);
<小时/>
没有索引
您可以简单地每次删除第一个值,一旦列表为空,就使用原始数组重新创建它。正如 Ole V.V.指针输出,由 Arrays.asList(E[])
生成的 List 不支持删除方法,因此有必要从中生成一个新实例。
这是一个使用此解决方案的快速而简单的类:
public class RandomList<E>{
E[] array;
List<E> list;
public RandomList(E[] array){
this.array = array;
buildList(array);
}
public E getRandom(){
if(list.isEmpty()) buildList(array);
return list.remove(0);
}
public void buildList(E[] array){
list = new ArrayList<E>(Arrays.asList(array));
Collections.shuffle(list);
}
}
测试是用这个小代码完成的:
Integer[] array = {1,2,3,4,5};
RandomList<Integer> rl = new RandomList(array);
int i = 0;
while(i++ < 10)
System.out.println(rl.getRandom());
关于java - 如何获取不重复的随机字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41697504/