【问题标题】:Select different random elements from an ArrayList of array of strings in java从java中字符串数组的ArrayList中选择不同的随机元素
【发布时间】: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


【解决方案1】:

您不使用随机化器对象,而是每次在循环中创建一个新对象。因此,请使用您创建的那个(避免每次都使用新的 Random 调用)。 试试:

public static void RandomSchedules(ArrayList<String[]> list)
{
    Random randomizer = new Random(System.currentTimeMillis());
    for(int i=1; i<11; i++)
    {
        String[] random = list.get(randomizer.nextInt(list.size()));
        System.out.println("Random Schedule " +  ":" + Arrays.toString(random));
    }
}

【讨论】:

  • 你的输入列表是什么?如果它只有一个 String [] (list.size() == 1),那么它会这样做,但是列表中的多个 string[] 会产生可变输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
相关资源
最近更新 更多