簡體   English   中英

Java索引數組超出范圍異常

[英]Java Index Array Out of Bounds Exception

這個循環很奇怪。

我在Java中運行它,它給出了索引超出范圍的異常。 我無法找到一個int l在源代碼中的任何地方聲明,我無法弄清楚它是什么,並發現它是合法的,它這樣聲明。

但是這里的問題是,我不明白這段代碼在做什么。 對於任何大小的resultSIList ,它都會給出ArrayIndexOutOfBoundsException

for (int i = offset, l = Math.min(i + maxItemsInOnePage, totalSIs); i < l; i++){
    resultSIList.get(i);
}

編輯 :謝謝大家。

這是我用來嘗試理解整個循環的可運行代碼。 是的,這是一塊可怕的垃圾。

public class IndexOutOfBoundsTest {
    public static void main(String args[]){
        int offset = 50;

        int maxItemsInOnePage = 50;

        int totalSIs = 50;

        final int buildThis = 15;

        List resultSIList = new ArrayList();

        // build list
        for(int zz = 0; zz < buildThis; zz ++){
            resultSIList.add("Hi " + zz);
        }

        try{
            for (int i = offset,
                    d = Math.min(i + maxItemsInOnePage, totalSIs);
                    i < d; i++){

               System.out.println(resultSIList.get(i));
           }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

此代碼將“ resulSIList”從“偏移”位置循環到“偏移+ maxItemsInOnePage”和“ totalSIs”的最小值。

如果offset> 0並且totalSIs = resultSIList.size(),我認為它不會給您超出范圍的異常。

在您的示例中,偏移量為50,列表大小僅為15。您必須檢查偏移量是否小於列表大小。

要獲取更多信息,可以添加一些日志來運行它:

System.out.println("offset: " + offset);
System.out.println("maxItemsInOnePage: " + maxItemsInOnePage);
System.out.println("totalSIs: " + totalSIs);
System.out.println("resultSIList.size(): " + resultSIList.size());
for (int i = offset, l = Math.min(i + maxItemsInOnePage, totalSIs); i < l; i++){
    System.out.println("i: " + i);
    resultSIList.get(i);
}

運行它應該可以使您了解一些問題; 最后打印的我超出范圍,通過分析前四個打印輸出,您應該找到問題所在。

當且僅當 totalSIs等於或小於resultSIList的大小時,它resultSIListresultSIList 仔細檢查該值。 這是一個帶有一些隨機值的工作示例:

List<Integer> resultSIList = Arrays.asList(1,2,3,4,5,6,7,8);
int totalSIs = resultSIList.size();
int maxItemsInOnePage = 2;
int offset = 1;

for (int i = offset, l = Math.min(i + maxItemsInOnePage, totalSIs); i < l; i++){
  resultSIList.get(i);
}

從添加的代碼中,我看到totalSIs比列表大小(= 15)大(= 50)。

您可以添加

 totalSIs = resultsSIList.size();

在for循環的后面快速修復。

檢查offset是否小於列表的大小。

您應該經常檢查索引i是否小於尺寸

for (int i = offset, l = Math.min(i + maxItemsInOnePage, totalSIs);
      i < l && i < resultSIList.size ();
      i++){
  resultSIList.get(i);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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