Your use of Random doesn't prevent an entry from being chosen more than once. If you are looking to simply randomize the order of the array, you may be well advised to generate a new array, populating it with the entries from the old one - removing one entry from the old at a time to create the new one.
Since array sizes are not mutable in Java, you may need to use some additional or an alternate data structure to keep track of which entries have already been returned.
A number of approaches that can be used to do this are available at Random shuffling of an array - complete with source code.
You could try something like this:
public static void shuffle(char[] characterArray){
final List<Character> charList = new ArrayList<>(characterArray.length);
for(final char c : characterArray){
charList.add(c);
}
Collections.shuffle(charList);
for(final char c : charList){
System.out.print(c);
}
}
The single-argument Collections.shuffle
call internally creates and uses a new Random()
. However, if you must "use" / show use of the Random class (or use an alternate source of randomness):
public static void shuffle(char[] characterArray){
final Random generator = new Random(12345);
final List<Character> charList = new ArrayList<>(characterArray.length);
for(final char c : characterArray){
charList.add(c);
}
Collections.shuffle(charList, generator);
for(final char c : charList){
System.out.print(c);
}
}
Now, I wouldn't use the single-argument Random constructor with a constant value, if you're looking for unpredictable outputs here.
Alternatively, you could follow the above suggestions in terms of approach to do something similar yourself without calling Collections.shuffle
. Reviewing the source code of Collections.shuffle
yourself could also be educational.