[英]Sorting ArrayList - IndexOutOfBoundsException -Java
我正在尝试根据我存储在另一个带有整数(结果)的arrayList中的值对具有字符串(PlayersNames)和imageIcons(PlayersIcons)的ArrayList进行排序。 如您所见,我得到了indexOutOfBoundsException但我不明白为什么。 也许早晨的耳环使我看不到朴素的事物。
ArrayList<String> PlayersNames=new ArrayList<String>;
ArrayList<ImageIcon> PlayersIcons=new ArrayList<ImageIcons>;
public void sortPlayers(ArrayList<Integer> results){
String tmp;
ImageIcon tmp2;
for (int i=0; i<PlayersNames.size(); i++) {
for (int j=PlayersNames.size(); j>i; j--) {
if (results.get(i) < results.get(i+1) ) { //IndexOutOfBoundsException!
tmp=PlayersNames.get(i+1);
PlayersNames.set(i+1,PlayersNames.get(i));
PlayersNames.set(i,tmp);
tmp2=PlayersIcons.get(i+1);
PlayersIcons.set(i+1,PlayersIcons.get(i));
PlayersIcons.set(i,tmp2);
}
}
}
}
当循环到达arrayList的末尾时,您试图使项目超出列表的末尾。 在这行上:
if (results.get(i) < results.get(i+1) ) {
如果i = 9,且arrayList具有10个项目,则results.get(9)将为您提供列表中的最后一个项目。 results.get(10)将尝试获取不存在的内容。
您可以使用Collections.sort(Pass ArrayList Here)
,而无需编写自己的方法。 Java提供了它。
最终, i
可以保留PlayersNames.size()-1
。 我只能假设results
的大小与PlayersNames
相同,或更PlayersNames.size() == results.size()
,就是PlayersNames.size() == results.size()
。
如果这是真的,那么最终您要在results
请求results.size()
个元素(通过results.get(i+1)
),这比results
还要多,因此抛出了IndexOutOfBoundsException 。
简而言之,如果结果包含N个项目,则使用索引N-1
访问第N个项目,但是您尝试访问的索引N
处的项目不存在。
尝试将外部循环更改为:
for (int i=0; i<PlayersNames.size()-1; i++) {
防止超支。
同样,您的内部循环似乎没有被使用,但是如果您尝试使用j
的第一个值访问数组中的某个内容,则出于相同的原因,您可能会遇到相同的问题。
for循环的最后一次迭代, i
将等于PlayersNames.size() - 1
。 在发生错误的那一行,您正在调用results.get(PlayersNames.size())
results.get(i + 1)
,其results.get(PlayersNames.size())
为results.get(PlayersNames.size())
。
我可以看到几个错误:
1)
i<PlayersNames.size()
那很好,但随后您使用
i+1
EVERYWHERE(不仅在if中),因此当您到达最后一个元素时,您将始终遇到indexOutOfBoundsException。
减小i的范围或删除+1;或者
2)你声明一个变量
Ĵ
你永远不会使用...
许多人给出了正确的理由。
有很多方法可以纠正此程序。 最简单的方法是仅将外循环迭代到n-1(其中n是ArrayList的大小)
for (int i=0; i<PlayersNames.size()-1; i++) {
使用地图,例如:
Map <String, ImageIcon>
排序可能比使用两个ArrayList更有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.