java如何使用索引
如何在 Java 中使用索引
Java 中索引的使用主要涉及数组、集合类(如 ArrayList、LinkedList)和字符串操作。索引通常用于直接访问或修改特定位置的元素。
数组中使用索引
数组通过下标(从 0 开始)访问元素:
int[] numbers = {10, 20, 30, 40};
int firstElement = numbers[0]; // 访问第一个元素(值为10)
numbers[1] = 25; // 修改第二个元素的值
集合类中使用索引
ArrayList 支持通过索引快速访问:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
String fruit = list.get(0); // 获取第一个元素("Apple")
list.set(1, "Mango"); // 修改第二个元素
LinkedList 虽然支持索引访问,但效率较低(需遍历):
import java.util.LinkedList;
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(100);
linkedList.add(200);
int value = linkedList.get(1); // 获取第二个元素(200)
字符串中使用索引
String 的 charAt() 方法获取指定位置的字符:
String text = "Hello";
char firstChar = text.charAt(0); // 'H'
索引的边界检查
访问索引时需确保不越界,否则抛出 IndexOutOfBoundsException:
if (index >= 0 && index < array.length) {
// 安全访问数组
}
if (index >= 0 && index < list.size()) {
// 安全访问列表
}
多维数组的索引
多维数组通过多个下标访问:
int[][] matrix = {{1, 2}, {3, 4}};
int value = matrix[0][1]; // 访问第一行第二列(值为2)
使用循环遍历索引
通过索引遍历集合或数组:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
注意事项
- 索引从 0 开始,最大有效值为
长度-1。 - 集合类中,
LinkedList的索引访问效率低于ArrayList。 - 字符串不可变,无法通过索引直接修改字符,需转换为
char[]操作。







