Tuesday, October 2, 2012

GWT Collections.shuffle Implementation

I've got to give a hand to Google, they have done a magnificent job implementing most of the standard Java classes and methods in Javascript through GWT, but every now and again I run into a common method that has yet to make the usage threshold of getting a GWT implementation. Today, I ran into a case where "Collections.shuffle" would be the cleanest solution to randomizing a list in GWT, but alas, GWT had no idea such a method existed, so I improvised.

 for(int index = 0; index < list.size(); index += 1) {  
    Collections.swap(list, index, Random.nextInt(list.size()));  
 }  

Clean and simple.