【发布时间】:2017-10-31 18:13:30
【问题描述】:
我是菜鸟。我必须从具有字符串数组的 ArrayList 中随机选择不同的元素。我尝试了几种不同的方法,但每次都选择相同的数组。这是我尝试过的方法。
public static void RandomSchedules(ArrayList<String[]> list)
{
Random randomizer = new Random();
for(int i=1; i<11; i++)
{
String[] random = list.get(new Random().nextInt(list.size()));
System.out.println("Random Schedule " + ":" + Arrays.toString(random));
}
}
我在上面的代码中也试过这个。
String[] random = list.get(randomizer.nextInt(list.size()));
但结果是一样的。
这是我从 Stack Overflow 尝试过的另一种方法
public static List<String[]> pickNRandom(ArrayList<String[]> lst, int n) {
List<String[]> copy = new LinkedList<String[]>(lst);
Collections.shuffle(copy);
return copy.subList(0, n);
}
我将上述函数称为,
List<String[]> randomPicks = pickNRandom(lst, 10);
谁能指导我如何获得不同的元素。
【问题讨论】:
-
听起来你可能有重复的数组。你检查内容了吗?
标签: java arrays arraylist random