Is there a kind of Java collection that the order of my fetching is random? For example, I put integer 1, 2, 3 into the collection and when I try to print them all the result can be "1 2 3","3 2 1" or "1 3 2"?
Random class is part of java. util package. An instance of java Random class is used to generate random numbers. This class provides several methods to generate random numbers of type integer, double, long, float etc. Random number generation algorithm works on the seed value.
Java Collections are the one-stop solutions for all the data manipulation jobs such as storing data, searching, sorting, insertion, deletion, and updating of data. Java collection responds as a single object, and a Java Collection Framework provides various Interfaces and Classes.
nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList. Now use this number as an index of the ArrayList. Use get () method to return a random element from the ArrayList using number generated from nextInt() method.
If you just want a random sequence you could use Collections.shuffle
List<Integer> list = new LinkedList(); //Add elements to list Collections.shuffle(list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With