一种有效的方式来洗牌Java中的JSON阵列? [英] An efficient way to shuffle a JSON array in java?
问题描述
这将是做到这一点的最好方法是什么?现在,我将我 JSONArray
来定制类,使用集合的
来执行操作,并将其转换回的ArrayList
。洗牌() JSONArray
,这似乎是太多的开销。
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.
答案可能只是实施
费雪耶茨洗牌它,但我的猜测是,这可能是这样做的话,我想避免重新发明轮子。
我看了看标准 JSON API 并的谷歌的GSON ,但他们似乎没有任何实现
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.
还有一个标准的阵列简单的选择在这个问题上这可能是方便的移植到Java,但是我会很高兴地听到你的意见。我很惊讶,查询 http://www.google.com/search?q = + java的洗牌+ jsonarray 没有和方法充斥了我。
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.
推荐答案
对不起张贴的答案,我自己的问题,但是现在,因为没有外的开箱快速的解决方案,我在我的实现根据从这个职位的code自身的静态随机播放功能:<一href=\"http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array-in-android/1520212#1520212\">Random在Android的一个数组的洗牌?。还在期待听到的最好的实现。这就是我所做的:
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 in Android ? . 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;
}
这篇关于一种有效的方式来洗牌Java中的JSON阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!