【发布时间】:2015-11-01 15:29:46
【问题描述】:
以下代码抛出异常:
public class Medicine {
private String name;
private Double dose;
private ArrayList<Time> time = new ArrayList<Time>();
private Unit unit;
private int index = 0;
public Time getNextTime() {
return time.get(index++);//it throws it in this line. It says Caused by: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
}
更新 1: 好吧好吧,我正在添加更多代码。以下调用异常抛出行:
(t = medicine.getNextTime())!= null
【问题讨论】:
-
您期望的结果是什么?为什么?
-
@Psherno 好吧,我截断了代码。我正在编写一个完整的 Android 应用程序。泄露项目的所有类和布局文件对我来说是不合适的。所以,我想,我会删除非错误代码并粘贴类的重要部分。请注意,时间是枚举类型。
-
因此,根据异常消息,我们可以看到您的列表有两个元素,并且您正在尝试读取索引为
2的元素。你认为这应该可行吗(记住索引从0开始)? -
根据您添加的代码,如果您使用不正确的索引,您似乎期望
time.get(index++)返回null。不幸的是,这不是真的,ArrayList.get通过抛出IndexOutOfBoundsException来处理无效索引,您可以在日志中清楚地看到这一点。