簡體   English   中英

使用Collections.min中的值進行索引時的IndexOutOfBoundsException

[英]IndexOutOfBoundsException when indexing with value from Collections.min

我試圖獲取最小值的索引,但是當第一個元素的最小值為570(索引= 0)時,我收到此錯誤。 我究竟做錯了什么?

碼:

//ArrayList of distanceList [570, 621, 716, 906, 1055, 1253, 1314, 1314]
ArrayList<Integer> distanceList = entry.getValue();
//min is 570
int min = Collections.min(distanceList);
int index = distanceList.get(min);

錯誤:

threw exception [java.lang.IndexOutOfBoundsException: Index: 570, Size: 8] with root cause
java.lang.IndexOutOfBoundsException: Index: 570, Size: 8
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.get(ArrayList.java:411) 

with int index = distanceList.get(min); 你是distanceListmin -th元素。

try int index = distanceList.indexOf(min); 代替

java.util.ArrayList.get(int index)方法返回此列表中指定位置的元素。

宣言

以下是java.util.ArrayList.get()方法的聲明

public E get(int index)

參數

index - 要返回的元素的索引。

例外

IndexOutOfBoundsException - 如果索引超出范圍。


  int min = Collections.min(distanceList);//this returns 570
  int index = distanceList.get(min);//you are passing 570 as index where array 

size為8,表示其索引為7.因此導致異常

發生此類錯誤是因為您嘗試訪問不存在的數組位置。初始位置索引為0(570為值),最后一個成員的大小為1。
然后,在您的情況下,您可以使用0到7之間的索引訪問位置。

您正在使用存儲在數組列表中的值作為索引。 這是不對的。 索引是元素存儲的位置(此處為整數值)

使用distancelist.indexOf(min)

暫無
暫無

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

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