How to select a random item from ArrayList in Java?

See English answers > randomly select an item from a list

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

At present, I do this, but because I need to use it again and again, is there a shorter way to do this?

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

Solution

It's easy to put your code in such a method

Random rand; // Global variable

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

It is called this in the main method;

int selected = randomItem(mylist);
System.out.println(selected);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>