Which would be the best way to do it? Right now, I convert my JSONArray
to an ArrayList
of a custom class, use Collections.shuffle()
to perform the action, and convert back to JSONArray
, which seems to be too much overhead.
The answer may be just to implement a Fisher-Yates shuffle for it, but my guess is that this may be already done so I would like to avoid reinventing the wheel. I looked at the standard JSON api and Google's Gson but they don't seem to have any implementation.
There are also simple options for a standard array in this question that could be easily ported to java, but I would gladly hear your input. I am amazed that the query http://www.google.com/search?q=java+shuffle+jsonarray did not flood me with methods.
Sorry for posting an answer to my own question, but right now, since there was no out-of-the-box quick solution, I'm implementing my own static shuffle function based on the code from this post: Random shuffling of an array . Still looking forward to hear about the best implementation. This is what I did:
public static JSONArray shuffleJsonArray (JSONArray array) throws JSONException {
// Implementing Fisher–Yates shuffle
Random rnd = new Random();
for (int i = array.length() - 1; i >= 0; i--)
{
int j = rnd.nextInt(i + 1);
// Simple swap
Object object = array.get(j);
array.put(j, array.get(i));
array.put(i, object);
}
return array;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With