java 如何从java中的arraylist中选择一个随机项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28841084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:15:37  来源:igfitidea点击:

How to pick a random item from a arraylist in java?

javarandomarraylist

提问by Adam

How can I pick a random item from a list of items in a array list, for example;

例如,如何从数组列表中的项目列表中选择一个随机项目;

ArrayList<Integer>  mylist= new ArrayList<Integer>();
mylist.add(19);
mylist.add(154);
mylist.add(112);
mylist.add(15);
mylist.add(112);

Currently, I am doing this but because I need to use this over and over again, is there a shorter way of do this?

目前,我正在这样做,但因为我需要一遍又一遍地使用它,有没有更短的方法来做到这一点?

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

回答by user253751

You can make a method that picks a random item from any list like this:

您可以创建一个从任何列表中随机选择一个项目的方法,如下所示:

static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
    return list.get(rand.nextInt(list.size()));
}

Creating a new Randomobject each time you want a random number is a bad practice. This only creates one and re-uses it.

Random每次想要随机数时都创建一个新对象是一种不好的做法。这只会创建一个并重新使用它。

Also, you can call it with any type of list - not just ArrayList<Integer>s.

此外,您可以使用任何类型的列表来调用它——而不仅仅是ArrayList<Integer>s。

回答by Lee Bradley

Simple, put your code in a method like this

很简单,把你的代码放在这样的方法中

Random rand; // Global variable

public static int randomItem(Arraylist<Integer> mylist) {
    rand = new Random(); 
    Integer randomInt = lista.get(rand.nextInt(lista.size()));
    return randomInt;
}

and call it like this in your main method;

并在您的主要方法中像这样调用它;

int selected = randomItem(mylist);
System.out.println(selected);