Fastest way to randomize an int array in Java

Is it possible to select a random element from one array and transfer it to another without the help of ArrayLists / Collections, etc. (if you cannot use shuffle in an array)? and make sure the item is not selected again? I was thinking about setting it to zero, it seems you cannot delete it, but I'm not sure.

Basically, I want myArray get shuffled or randomized, and I decided that the best way is to pull them from one randomly and add them to a new one ...

+4
source share
3 answers

You can use Collections.shuffle(List) to shuffle the array:

 Integer[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Collections.shuffle(Arrays.asList(data)); System.out.println(Arrays.toString(data)); 

will be printed, for example. [6, 2, 4, 5, 10, 3, 1, 8, 9, 7].

Arrays.asList will not create a new list, but a List interface wrapper for the array, so changes to the list will also be passed to the array.

+7
source

You can use the Collections.shuffle () method to shuffle the list.

+3
source

- You can use Collection as a List , and then use the shuffle() method.

- Or, if you want to stick to an array, you first need to convert the array to a list, and then use the shuffle () method.

For instance:

 Integer[] arr = new Integer[10]; List<Integer> i = new ArrayList<Integer>(Arrays.asList()); Collections.shuffle(i); 
+2
source

All Articles