gpt4 book ai didi

java - 排序 ArrayList - IndexOutOfBoundsException - Java

转载 作者:行者123 更新时间:2023-12-01 06:37:01 26 4
gpt4 key购买 nike

我试图根据我存储在另一个带有整数(结果)的 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) 将尝试获取不存在的东西。

关于java - 排序 ArrayList - IndexOutOfBoundsException - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4676953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com