我正在尝试创建一种手动洗牌的方法。该列表被洗牌,但每次都会产生相同的结果。代码示例如下:
package ch11;
import java.util.ArrayList;
import java.util.Arrays;
public class Chapter_11_E07_ShuffleArrayList {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8};
ArrayList<Integer> intList = new ArrayList<>(Arrays.asList(array));
System.out.println("Before shuffle: ");
for (Integer x: intList)
System.out.print(x + " ");
shuffle(intList);
System.out.println("\nAfter shuffle: ");
for (Integer x: intList)
System.out.print(x + " ");
}
public static void shuffle(ArrayList<Integer> intList) {
// Simple solution
// java.util.Collections.shuffle(intList);
// Manual shuffle
for (Integer x: intList) {
int newIndex = (int) Math.random() * intList.size();
Integer temp = intList.get(x);
intList.set(x, intList.get(newIndex));
intList.set(newIndex, temp);
}
}
}
它似乎在某种程度上有效,但Math.random * intList.size()
每次产生相同的随机索引?输入非常受欢迎!
答案 0 :(得分:12)
这是因为
int newIndex = (int)(Math.random() * intList.size());
没有正确括号。它应该是
nextInt(intList.size())
为避免此类简单错误,请制作新的Random
对象,然后致电{{1}}。
答案 1 :(得分:1)
要显示我在上述评论中的含义,请输入以下代码:
for (Integer x: intList) {
int newIndex = (int) (Math.random() * intList.size());
int oldIndex = intList.indexOf(x);
Integer temp = intList.get(newIndex);
intList.set(newIndex, x);
intList.set(oldIndex, temp);
}