【发布时间】:2016-06-27 10:51:58
【问题描述】:
我正在尝试随机打乱列表中的整数集合,并且我想出了两种打乱方法来完成这项工作。但是,我不确定哪一个效果更好?有没有人有任何cmets或建议?
public class TheCollectionInterface {
public static <E> void swap(List<E> list1, int i, int j) {
E temp = list1.get(i);
list1.set(i, list1.get(j));
list1.set(j, temp);
}
// Alternative version:
// public static void shuffling(List<?> list, Random rnd){
// for(int i = list.size(); i >= 1; i--){
// swap(list, i - 1, rnd.nextInt(i));
// }
// }
public static <E> void shuffling(List<E> list1, Random rnd) {
for (int i = list1.size(); i >= 1; i--){
swap(list1, i - 1, rnd.nextInt(list1.size()));
}
}
public static void main(String[] args) {
List<Integer> li2 = Arrays.asList(1,2,3,4,5,6,7,8,9);
Random r1 = new Random();
TheCollectionInterface.shuffling(li2, r1);
System.out.println(li2);
}
}
【问题讨论】:
标签: java list random collections