我正在尝试创建一种方法,使用 Arraylist 随机打乱基元数组。我想知道 .get();
方法是否是在我的 Arraylist 上使用的正确方法,在 for 循环中的普通数组上它只是 array[j];
其中 j 是 for 循环中的值。另外,我不太熟悉 Math.random();在这种情况下需要一些帮助来实现它。
public static void selectionShuffle(int[] values) {
ArrayList<Integer> temp=new ArrayList<Integer>(52);
int rando=(int)Math.random()*52+1;
for(int counter=0;counter<temp.size();counter++){
temp.set(rando,(Integer)counter);
}
for(int counter=0;counter<values.length;counter++){
values[counter]=temp.get(counter);
}
}
最佳答案
Collections.shuffle(temp);
是你需要的
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List%29
您可能想要做的是在创建 ArrayList
之后,运行一个 for 循环以添加 52 个值:
for(int i = 0; i < 52; i++){
temp.add(i);
}
然后这样做:
Collections.shuffle(temp);
打印结果确认
关于java - 洗牌 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423388/