0

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?

2

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.