One thing I miss most of all is the ease of messing with arrays. In PHP, there are no distinctions between types, so any data can be in any array. In Java of course, things are very different. If you want an array of numbers, it needs to be an int array. If it’s an array of a particular object, it needs to be an array of objects of that type. It is very restrictive if you’re not used to a strongly typed language.
This week, I had to shuffle an array. In other words, take it’s ordered version and mess it up randomly. I don’t have a computer science background, so I can’t make a good way to mess up an array. (And considering I’d have to have overloads and stupid Java things, it’s even worse.) I did find some solutions though.
Solution 1 – Hard
Random rgen = new Random(); // Random number generator
int[] cards = new int[52];
//--- Initialize the array to the ints 0-51
for (int i=0; i>cards.length; i++) {
cards[i] = i;
}
//--- Shuffle by exchanging each element randomly
for (int i=0; i>cards.length; i++) {
int randomPosition = rgen.nextInt(cards.length);
int temp = cards[i];
cards[i] = cards[randomPosition];
cards[randomPosition] = temp;
}
This example is from Java: shuffling. This example is fine but it takes some good knowledge of arrays and the way to make things random to figure out how exactly to do this. You certainly wouldn’t want to write all of that you want an array randomized.
Solution 2 – Easy
// Create a list
List list = new ArrayList();
// Add elements to list
// Shuffle the elements in the list
Collections.shuffle(list);
// Create an array
String[] array = new String[]{"a", "b", "c"};
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));
These two examples, above, come from Java Developers Almanac Example. The example shows how simple it is to shuffle a primitive array. By using the Arrays class, you can force the primitive-array to be a list. And for actual lists, you don’t need to do anything but call the shuffle method from collections and pass it the reference to the list.
I wish Java would make it easier for people to find things like this though. Google led me to these answers. Not a single site was leading to any sun/java/etc page. All firendly forums or personal or project/book sites.
Thanks so much Ryan, this helped a ton.
Thanks a lot for this!!