Basically, let's say I have an int array that can hold 10 numbers. Which mean I can store 0-9 in each of the index.(each number only once).
If I run the code below:
int[] num = new int[10];
for(int i=0;i<10;i++){
num[i]=i;
}
my array would look like this: [0],[1],.....,[8],[9]
But how do I randomize the number assignment each time I run the code? For example, I want the array to look something like: [8],[1],[0].....[6],[3]
Collections class has an efficient method for shuffling:
Make it a
List<Integer>
instead of an array, and use Collections.shuffle() to shuffle it. You can build the int[] from the List after shuffling.If you really want to do the shuffle directly, search for "Fisher-Yates Shuffle".
Here is an example of using the List technique: