gpt4 book ai didi

java - 洗牌 ArrayList

转载 作者:行者123 更新时间:2023-11-29 04:50:56 26 4
gpt4 key购买 nike

我正在尝试创建一种方法,使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com