IndexOutOfBoundsException
是 Java 中常见的运行时异常,表示访问了无效的索引(数组、集合、字符串等)。本文将从原因分析到解决方法,并提供真实案例和代码示例,帮你彻底解决这个问题。
IndexOutOfBoundsException
的常见场景:数组越界
:
集合越界
:
List
等集合使用无效索引。字符串索引越界
:
charAt()
或 substring()
。迭代器错误
:
检查索引合法性
:
添加边界检查
:
修正循环条件
:
处理空或空集合
:
问题代码:
int[] arr = {1, 2, 3};
int value = arr[3]; // 数组索引超出范围
解决方案:
int[] arr = {1, 2, 3};
if (arr.length > 3) {
int value = arr[3];
System.out.println(value);
} else {
System.out.println("Index out of bounds!");
}
List
索引操作问题代码:
List list = new ArrayList<>(List.of("A", "B", "C"));
String value = list.get(5); // 索引超出范围
解决方案:
List list = new ArrayList<>(List.of("A", "B", "C"));
int index = 5;
if (index >= 0 && index < list.size()) {
String value = list.get(index);
System.out.println(value);
} else {
System.out.println("Invalid index: " + index);
}
String
的子串操作问题代码:
String str = "Hello, Java!";
String sub = str.substring(5, 20); // 索引超出范围
解决方案:
String str = "Hello, Java!";
int start = 5, end = 20;
if (start >= 0 && end <= str.length() && start < end) {
String sub = str.substring(start, end);
System.out.println(sub);
} else {
System.out.println("Invalid substring range!");
}
问题代码:
int[] arr = {1, 2, 3};
for (int i = 0; i <= arr.length; i++) { // 循环条件错误
System.out.println(arr[i]);
}
解决方案:
int[] arr = {1, 2, 3};
for (int i = 0; i < arr.length; i++) { // 修正循环条件
System.out.println(arr[i]);
}
问题代码:
int[] arr = null;
System.out.println(arr[0]); // 数组为空
解决方案:
int[] arr = null;
if (arr != null && arr.length > 0) {
System.out.println(arr[0]);
} else {
System.out.println("Array is null or empty!");
}
案例描述: 在分页查询时,返回的记录列表为空或索引超出范围,导致异常。
问题代码:
List data = new ArrayList<>();
String firstElement = data.get(0); // 列表为空
解决方案:
List data = new ArrayList<>();
if (!data.isEmpty()) {
String firstElement = data.get(0);
System.out.println("First element: " + firstElement);
} else {
System.out.println("List is empty!");
}
以下是一个包含数组、集合、字符串的综合示例:
public class IndexOutOfBoundsExample {
public static void main(String[] args) {
// 数组操作
int[] arr = {10, 20, 30};
int index = 3;
if (index >= 0 && index < arr.length) {
System.out.println("Array value: " + arr[index]);
} else {
System.out.println("Array index out of bounds!");
}
// 集合操作
List list = new ArrayList<>(List.of("A", "B", "C"));
int listIndex = 2;
if (listIndex >= 0 && listIndex < list.size()) {
System.out.println("List value: " + list.get(listIndex));
} else {
System.out.println("List index out of bounds!");
}
// 字符串操作
String str = "Hello";
int start = 1, end = 6;
if (start >= 0 && end <= str.length() && start < end) {
System.out.println("Substring: " + str.substring(start, end));
} else {
System.out.println("String index out of bounds!");
}
}
}
IndexOutOfBoundsException
的有效方法:[0, size-1]
内。通过以上方法,可以有效解决 IndexOutOfBoundsException
异常问题,提高代码健壮性!