ArrayList beds = new ArrayList(49);
public Patient getPatient(int bedNumber) {
if (beds.get(bedNumber) != null) {
return (Patient) beds.get(bedNumber);
}
else {
return null;
}
}
我遇到了一个问题,我似乎无法让 Java 在方法中输出 null。
假设我将一名患者分配给床位 ArrayList 中的某个项目,然后尝试使用上面创建的 getPatient 方法获取第 11 张床位的患者,但是您不能这样做,因为尚未添加 11 名患者。当我尝试执行此操作而不是 java.lang.IndexOutOfBoundsException 时,如何使其输出 null。
最佳答案
首先,编译器与此无关,因为显示 IndexOutOfBoundsException 的是 JVM。
您应该做的是根据 ArrayList 的大小检查 bedNumber,而不是检查不存在(超出范围)的 ArrayList 项是否为 null。所以做简单的整数数学。
即,
if (bedNumber > 0 && bedNumber < beds.size()) {
// do your stuff here
} else {
// myself, I'd throw an exception here, not return null
}
关于java - 编译器输出 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262851/