[英]ArrayList Index out of bounds but actually not?
So I am having a very confusing bug with my java code right now. 所以我现在在我的Java代码中遇到一个非常令人困惑的错误。 I am just going to insert the important parts of my code, and explain what it should do:
我只是要插入代码的重要部分,并解释它应该做什么:
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)
Now, the following code looks a bit weird, its basically supposed to read two values of superstarKandidaten which aren't the same. 现在,下面的代码看起来有些怪异,它基本上应该读取两个不相同的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);
}
I am not going to write the rest of the code since it is unnecesarry, here is the output: 我不需要编写其余代码,因为它是不必要的,这里是输出:
{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)
Whatever the actual size of your list is, this snippet contains a flaw: 无论列表的实际大小如何,此代码段都包含一个缺陷:
if (i + 1 > superstarKandidaten.size()) i = 0; else i++; System.out.println(i); person2 = superstarKandidaten.get(i);
The if
allows i
to reach super....size()
, while valid indices are in the range of 0
... super...size()-1
. if
允许i
达到super....size()
,而有效索引的范围是0
... super...size()-1
。
eg i=3
, super...size()=4
, 3+1>4?
例如
i=3
, super...size()=4
3+1>4?
No, i=4
. 不,
i=4
。 Then super...get(4)
dies. 然后
super...get(4)
死亡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.