Hi guys, so I have the following piece of code:
public class Test{ public static void main (String args[]){ int[] myList = {1,2,3,4,5}; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] +" before"); int index = (int) (Math.random()* myList.length); int temp = myList[i]; myList[i] = myList[index]; myList[index] = temp; System.out.println(myList[i] +"after swap"); } } }
I have seen this from a Java book which says this is one way to shuffle the items in a given array. I don't believe it works though as I have tried it for myself and the Math.random() method is basically changing the values of the array cells and at the end I get a new array, say: {2,3,4,5,3}
Can somebody tell me some good way of shuffling array items? I am still quite new to programming so would appreciate some simple answer! (if possible )