我正在尝试创建一个单词列表,我想随机选择一个用于String。这是我现在拥有的:
private List<String> words = new ArrayList<String>();
public void someMethod() {
words.addAll(Arrays.asList("string1", "string2", "string3");
for (String s : words) {
// What now? How would I pick a random string from the list
// Also, if I shouldn't loop through the words, please tell me
System.out.println(randomString);
}
}
答案 0 :(得分:1)
您可以在0和列表大小之间生成一个随机int
,然后在该索引处获取该元素。
words.addAll(Arrays.asList("string1", "string2", "string3");
String randomString = words.get(ThreadLocalRandom.current().nextInt(0, words.size()));
ThreadLocalRandom.nextInt(origin, bound)
返回指定原点(包括)和指定边界(不包括)之间的伪随机int值。