我有下面这个方法根据我的JSON条目的大小生成随机数,每个数字可能只会来一次。我投了3次这个方法,因为我需要生成3个随机数,这个数应该是相互不同的。Android:错误java.lang.IndexOutOfBoundsException无效的位置
有时它的工作原理,但有时它给我的logcat的这个错误:错误java.lang.IndexOutOfBoundsException无效位置 ,这让我的应用程序崩溃。
任何人都可以帮我解决我的问题吗?谢谢!
int max = prjcts.size();
List<Integer> indices = new ArrayList<Integer>(max);
for(int c = 1; c < max; ++c)
{
indices.add(c);
}
int arrIndex = (int)((double)indices.size() * Math.random());
int randomIndex1 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex2 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex3 = indices.get(arrIndex);
indices.remove(arrIndex);
@KPBird: 所以我改变我的代码就像你告诉我,但它仍然给我的错误soemtime: 我缺少的东西?
Random r = new Random();
int arrIndex = r.nextInt(indices.size());
int randomIndex1 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex2 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex3 = indices.get(arrIndex);
indices.remove(arrIndex);
因此,对我来说,每次调用方法时都会创建arrIndex2,arrIndex3并将其删除,这样会更好。我对么? – hectichavana 2011-05-06 08:55:59
只需将数字放在索引中,调用Collections.shuffle(indices),然后取第一个X数字。随机播放会将它们随机分配给你。 – 2011-05-06 09:02:16