在Java中,判断数组下标是否越界通常有以下几种方法:
使用数组长度进行判断
int[] array = {1, 2, 3, 4, 5};
int index = 3;
if (index >= 0 && index < array.length) {
// 下标在有效范围内
int value = array[index];
System.out.println("数组元素值为: " + value);
} else {
System.out.println("数组下标越界!");
}
使用try-catch捕获异常
int[] array = {1, 2, 3, 4, 5};
int index = 5;
try {
int value = array[index];
System.out.println("数组元素值为: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界!");
}
使用断言(assert)
int[] array = {1, 2, 3, 4, 5};
int index = 3;
assert index >= 0 && index < array.length : "数组下标越界!";
int value = array[index];
System.out.println("数组元素值为: " + value);
使用Java集合框架(如果使用集合而非原始数组):
List
list = Arrays.asList(1, 2, 3, 4, 5); int index = 3;
if (index >= 0 && index < list.size()) {
int value = list.get(index);
System.out.println("列表元素值为: " + value);
} else {
System.out.println("列表下标越界!");
}