【问题标题】:Get random number from ArrayList? [closed]从 ArrayList 中获取随机数? [关闭]
【发布时间】:2013-10-13 15:38:56
【问题描述】:
ArrayList<Integer>  lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);

例如,我在数组列表中获得了这 3 个数字,我想随机获得其中一个。 这怎么可能?

【问题讨论】:

标签: java math random arraylist


【解决方案1】:

使用 Random 类的一种方法:

ArrayList<Integer>  lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);

Random r = new Random();
System.out.println(lista.get(r.nextInt(lista.size())));

或使用随机播放:

ArrayList<Integer>  lista = new ArrayList<Integer>();
lista.add(159);
lista.add(170);
lista.add(256);

Collections.shuffle(lista);
System.out.println(lista.get(0));

【讨论】:

    【解决方案2】:

    您可以利用Random 生成一个int 用作随机索引。

    Random rand = new Random();
    Integer randomInt = lista.get(rand.nextInt(lista.size()));
    

    这里,rand.nextInt(lista.size()) 会在0size - 1 之间生成一个随机索引。

    参考
    Random#nextInt(int)

    返回一个伪随机、均匀分布的 int 值,介于 0(inclusive)和指定值(exclusive)之间,取自该随机数生成器的序列。

    【讨论】:

      【解决方案3】:

      这个想法是生成一个新的随机索引并使用该随机索引从数组中获取随机数。

      为此

      1. 使用Math.random() 生成一个随机数,它返回一个带正号的双精度值,大于或等于0.0 且小于1.0。
      2. 将随机值调整到列表的开始索引和结束索引之间。为此,我们将 double 值乘以列表的大小并将其转换为整数,因为列表索引是整数。

      这给了我们以下代码。

      int randomIndex = (int)(Math.random() * lista.size());
      
      System.out.println(lista.get(randomIndex));
      

      请注意,这里生成的随机数并不是真正随机的,而是使用伪随机生成器生成的,足以满足大多数日常使用。

      如果您有兴趣,可以在此处阅读更多关于 PRNG 的信息:)

      【讨论】:

      • 这返回索引而不是值本身,这是我现在需要的。谢谢
      【解决方案4】:

      对列表中的元素数量使用随机数并将其用作索引。

      【讨论】:

        【解决方案5】:

        这样做:

        Random rn = new Random();
        int i = rn.nextInt() % lista.size();
        System.out.println(lista.get(i));
        

        【讨论】:

          猜你喜欢
          • 2017-08-13
          • 2014-06-01
          • 2021-07-31
          • 1970-01-01
          • 1970-01-01
          • 2014-04-04
          • 2015-03-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多