簡體   English   中英

排序ArrayList-IndexOutOfBoundsException -Java

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM