Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java random collection

Tags:

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"?

like image 452
Sefler Avatar asked Jun 09 '09 11:06

Sefler


People also ask

What is random class in Java?

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.

What are collections in Java?

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.

How do you get random from ArrayList?

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.


1 Answers

If you just want a random sequence you could use Collections.shuffle

    List<Integer> list = new LinkedList();     //Add elements to list     Collections.shuffle(list); 
like image 97
Silfverstrom Avatar answered Sep 19 '22 12:09

Silfverstrom