Java – get random numbers from ArrayList?
•
Java
ArrayList<Integer> lista = new ArrayList<Integer>();
ArrayList<Integer> lista = new ArrayList<Integer>(); lista.add(159); lista.add(170); lista.add(256);
For example, I get these three numbers in my ArrayList, and I want to get one of them at random How is that possible?
Solution
One way is to use the random class:
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())));
Or use shuffle:
ArrayList<Integer> lista = new ArrayList<Integer>(); lista.add(159); lista.add(170); lista.add(256); Collections.shuffle(lista); System.out.println(lista.get(0));
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
二维码