如何修复java.lang.IndexOutOfBoundsException

线程“main”中的exceptionjava.lang.IndexOutOfBoundsException:索引:0,大小:0,java.util.ArrayList.rangeCheck(ArrayList.java:604)

符合arraylist.java

private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } 

排队

 List lstpp = getResult(pp) ; System.out.println("=====Persegi Panjang===="); System.out.println("luas = "+((Integer)lstpp.get(0))); 

请帮忙

您想从空数组中获取元素。 这就是为什么Size: 0来自exception

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

所以你不能做lstpp.get(0)直到你填充数组。

lstpp是空的。 您无法访问空列表的第一个元素。

通常,您可以检查size > index

在您的情况下,您需要检查lstpp是否为空。 (你可以使用!lstpp.isEmpty()

您在列表中没有任何元素,因此无法访问第一个元素。

您正在尝试访问空数组的第一个元素lstpp.get(0) 。 只需在数组中添加一个元素,然后在访问元素之前检查!lstpp.isEmpty()

发生此错误是因为列表lstpp为空(索引0处为Nothing)。 因此,你的getResult()函数中有一个错误,或者空列表是正常的,你需要处理这种情况(通过检查列表的大小,或捕获exception)。

 for ( int i=0 ; i<=list.size() ; i++){ ....} 

通过执行for for循环,循环将执行抛出exception作为IndexOutOfBoundException原因,假设列表大小为10,所以当索引i将达到10时,即当i = 10时将抛出exception导致index=size ,即i=size并且已知Java认为索引从0,1,2 ...等开始,Java同意的表达式是index < size 。 因此,这种exception的解决方案是将循环中的语句设为i

 for ( int i=0 ; i