【问题标题】: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()) 会在0 和size - 1 之间生成一个随机索引。
参考:
Random#nextInt(int)
返回一个伪随机、均匀分布的 int 值,介于 0(inclusive)和指定值(exclusive)之间,取自该随机数生成器的序列。
【解决方案3】:
这个想法是生成一个新的随机索引并使用该随机索引从数组中获取随机数。
为此
- 使用
Math.random() 生成一个随机数,它返回一个带正号的双精度值,大于或等于0.0 且小于1.0。
- 将随机值调整到列表的开始索引和结束索引之间。为此,我们将 double 值乘以列表的大小并将其转换为整数,因为列表索引是整数。
这给了我们以下代码。
int randomIndex = (int)(Math.random() * lista.size());
System.out.println(lista.get(randomIndex));
请注意,这里生成的随机数并不是真正随机的,而是使用伪随机生成器生成的,足以满足大多数日常使用。
如果您有兴趣,可以在此处阅读更多关于 PRNG 的信息:)
【解决方案5】:
这样做:
Random rn = new Random();
int i = rn.nextInt() % lista.size();
System.out.println(lista.get(i));