Shuffle Array using Random Class
We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.
To shuffle an array in Java, you can use the java.util.Collections class, which provides a shuffle() method. Here’s an example of how you can shuffle an array:
<span class="hljs-keyword">import</span> java.util.Arrays;
<span class="hljs-keyword">import</span> java.util.Collections;
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ArrayShuffler</span> {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
Integer[] array = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>};
<span class="hljs-comment">// Shuffle the array</span>
Collections.shuffle(Arrays.asList(array));
<span class="hljs-comment">// Print the shuffled array</span>
System.out.println(Arrays.toString(array));
}
}
In this example, we have an array of integers array. We use Arrays.asList() to convert the array to a list, which is required by the shuffle() method. Then, we call Collections.shuffle() passing in the list, which shuffles the elements randomly. Finally, we print the shuffled array using Arrays.toString().
Note that shuffle() modifies the original array in place. If you want to create a shuffled copy of the array without modifying the original, you can create a new ArrayList, shuffle it, and then convert it back to an array if necessary.
