I'd like to be able to randomize the order of an array of objects, but I don't know how to do it without losing information of the object — i.e. The objects in the randomized array must be identical in terms of their variables/fields to the unrandomized array. So: What's the easiest way to randomize the order of an array of (user-defined) objects?
Asked
Active
Viewed 1,114 times
0
-
3Does this answer your question? [Random shuffling of an array](https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array) – Fureeish Dec 24 '19 at 02:48
-
The accepted answer of this question should help you: [How to shuffle the contents of an array](https://stackoverflow.com/questions/22312827/how-to-shuffle-the-contents-of-an-array) – Malte Hartwig Dec 24 '19 at 02:48
1 Answers
1
We have java.util.Collections.shuffle() method to shuffle elements in a list object.
Here is the working example for your reference
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
System.out.println("list before shuffle " + list);
Collections.shuffle(list);
System.out.println("list after shuffle for first time" + list);
Collections.shuffle(list);
System.out.println("list after shuffle for second time" + list);
output:
list before shuffle [1, 2, 3, 4, 5, 6, 7, 8]
list after shuffle for first time[4, 6, 1, 3, 7, 5, 2, 8]
list after shuffle for second time[1, 5, 6, 7, 2, 8, 3, 4]

Seshidhar G
- 265
- 1
- 9
-
Will this work with a user-defined object, without the objects losing any information (field values)? Either way, thanks for the answer and I'll try it out :) – Hazel Dec 24 '19 at 14:11