tags:

views:

395

answers:

4

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

+3  A: 

Take a normal collection and shuffle it, then iterate over it in a normal way.

You can use java.util.Collections.shuffle(List<T>) to do the shuffling.

Jon Skeet
Well, your first answer confused me because I don't aware of the java.util.Collections. I'm a fresh man, you know.
Sefler
+11  A: 

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

    List<Integer> list = new LinkedList();
    //Add elements to list
    Collections.shuffle(list);
Silfverstrom
This is one case where you might want to use `ArrayList` -- from the description of the algorithm you want fast random access.
Kathy Van Stone
+2  A: 

Just shuffle the collection.

If the collection must stay in order you could access elements at random indices, but then you have to keep track of ones you've used before (maybe, it depends on your application), and this can be very inefficient. A better solution, if memory is no obstacle, would be to just make a copy and shuffle that.

Bill the Lizard
+1  A: 

Not that I'm aware of. You could always put the values in a list, and use Collections.shuffle to put the values into a random order.

Tom