duk*_*vin 14 java arrays indexoutofboundsexception
我正在尝试检查数组位置是否超出范围,最简单的方法是什么?
int[] arr;
populate(arr);
if(arr[-1] == null)
//out of bounds!
Run Code Online (Sandbox Code Playgroud)
会这样的吗?
我很确定这可以通过trycatch或扫描仪完成,但对于一个简单的小程序,还有另外一种方法吗?
ars*_*jii 34
绝对不要使用try-catch.只需使用:
boolean inBounds = (index >= 0) && (index < array.length);
Run Code Online (Sandbox Code Playgroud)
使用try-catch实现该方法需要捕获一个ArrayIndexOutOfBoundsException,这是一个未经检查的异常(即子类RuntimeException).这些异常应该永远(或至少是非常罕见)被捕获和处理.相反,应该首先防止它们.
换句话说,未经检查的异常是您的程序不希望从中恢复的异常.现在,这里和那里可以有例外(没有双关语).例如,通常通过调用字符串Integer.parseInt()并捕获潜力NumberFormatException(未选中)来检查字符串是否可以作为整数进行比较.这被认为是可以的,但在做这样的事情之前总是三思而后行.
不,那会导致异常。
相反,做
if (x < 0 || x >= arr.length) {
//x is out of bounds!
}
Run Code Online (Sandbox Code Playgroud)