[英]ArrayList Index out of bounds but actually not?
所以我現在在我的Java代碼中遇到一個非常令人困惑的錯誤。 我只是要插入代碼的重要部分,並解釋它應該做什么:
ArrayList<String> superstarKandidaten = new ArrayList<>(freundesliste.keySet()); //there are exactly 5 keys in freundesliste, and after checking the content of superstarKandidaten, it gives me 5 different values (everything how I wanted it to be)
現在,下面的代碼看起來有些怪異,它基本上應該讀取兩個不相同的superstarKandidaten值。
int i = 0;
while (superstarKandidaten.size() > 1) {
if (i + 1 > superstarKandidaten.size()) i = 0; else i++;
System.out.println(i);
person1 = superstarKandidaten.get(i);
System.out.println(person1);
if (i + 1 > superstarKandidaten.size()) i = 0; else i++;
System.out.println(i);
person2 = superstarKandidaten.get(i); // <-- this is where the error happens according to the error message. (this is Ausrechnen.java:24
System.out.println(person2);
if (person1.equals(person2)) {
if (i + 1 > superstarKandidaten.size()) {
i = 0;
}else i++;
person2 = superstarKandidaten.get(i);
}
我不需要編寫其余代碼,因為它是不必要的,這里是輸出:
{Knuth=null Turing Dijkstra, Hoare=null Turing Dijkstra Codd, Turing=Hoare Dijkstra, Codd=null Turing Dijkstra Knuth, Dijkstra=null} // this is freundesliste
[Knuth, Hoare, Turing, Codd, Dijkstra] //this is superstarKandidaten
1 //this is i
Hoare //this is person1
2 //this is i
Turing //this is person2
3
Dijkstra
4
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 4
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:458)
at Ausrechnen.superstar(Ausrechnen.java:24)
at Main.main(Main.java:22)
無論列表的實際大小如何,此代碼段都包含一個缺陷:
if (i + 1 > superstarKandidaten.size()) i = 0; else i++; System.out.println(i); person2 = superstarKandidaten.get(i);
if
允許i
達到super....size()
,而有效索引的范圍是0
... super...size()-1
。
例如i=3
, super...size()=4
3+1>4?
不, i=4
。 然后super...get(4)
死亡。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.