排序ArrayList-IndexOutOfBoundsException-Java

排序ArrayList-IndexOutOfBoundsException-Java,java,sorting,arraylist,Java,Sorting,Arraylist,我试图根据存储在另一个带有整数(结果)的ArrayList中的值,对带有字符串(playerName)和图像图标(playerIcons)的ArrayList进行排序。 正如你所看到的,我有一个indexOutOfBoundsException,但我不明白为什么。也许清晨的来临让我看不到简单的东西 ArrayList<String> PlayersNames=new ArrayList<String>; ArrayList<ImageIcon> Players

我试图根据存储在另一个带有整数(结果)的ArrayList中的值,对带有字符串(playerName)和图像图标(playerIcons)的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 PlayerNames=新的ArrayList;
ArrayList PlayersIcons=新的ArrayList;
公共无效排序层(ArrayList结果){
串tmp;
图像图标tmp2;
对于(int i=0;ii;j--){
如果(results.get(i)
当循环到达arrayList的末尾时,您正试图使一个项目超过列表的末尾。在这一行:

if (results.get(i) < results.get(i+1) ) {
if(results.get(i)

如果i=9,对于包含10项的arrayList,results.get(9)将给出列表中的最后一项。results.get(10)将尝试获取不存在的内容。

最终
i
可以保存
PlayersNames.size()的值-1
。我只能假设
results
的大小与
PlayersNames
相同,或者更确切地说是
PlayersNames.size()==results.size()

如果这是真的,那么最终您将请求
结果中的
results.size()
-th元素(通过执行
results.get(i+1)
),它比
results
保持的值多一个,因此将引发IndexOutOfBoundsException

更简单地说,如果结果包含N个项目,则使用索引
N-1
访问第N个项目,但您尝试在索引
N
处访问该项目,该索引不存在

尝试将外部循环更改为:

for (int i=0; i<PlayersNames.size()-1; i++) {

for(int i=0;ifor循环的最后一次迭代,
i
将等于
PlayersNames.size()-1
。在发生错误的行上,您调用的是
results.get(i+1)
,它的计算结果为
results.get(PlayersNames.size())

(一)

无处不在(不仅仅是在if中),所以当你到达最后一个元素时,你总是会遇到indexOutOfBoundsException

减小i的范围或删除+1

(二) 您声明了一个变量

j


如果您从未使用过…

您可以使用
Collections.sort(在此处传递ArrayList)
,您不需要编写自己的方法。Java提供了它。

许多人都给出了正确的理由

有很多方法可以纠正这个程序。 最简单的方法是只迭代外循环直到n-1(其中n是ArrayList的大小)

for(int i=0;i使用类似于映射的:

Map <String, ImageIcon>
Map

可能对排序更有用,而不是使用两个ArrayList。

很明显,您已经离开了结果列表的末尾,但是您还没有发布调用sortPlayers()的代码因此,我们无法确定该列表应该有多大。它是否与PlayersNames大小相同?如果是,那么循环的最后一次迭代,即i==PlayersNames.size()-1,将导致您越界,因为尝试调用results.get(i+1)对结果列表来说太多了。问题是我不想只对ArrayList进行排序。我想根据结果ArrayList对其进行排序。只要想想结果就是玩家掷骰子时的结果,玩家就知道他们的名字。我想做的不是只对他们的名字进行排序,而是根据他们掷d的结果对他们的名字列表进行排序ice.Thanx但在其他情况下,当我需要两个ArrayList时,如何使用map?:/这次我如何使用j?我只尝试根据bubblesort对其进行排序:/
i+1
    for (int i=0; i<PlayersNames.size()-1; i++) {
Map <String, ImageIcon>