跳到主要内容
版本:1.0

数组

数组是长度固定、元素类型相同的容器,元素通过下标访问,下标从 0 开始。

声明与初始化​

// 方式一:指定长度,元素为默认值(int 为 0)
int[] nums = new int[5];

// 方式二:直接给出初始值,长度自动推断
int[] scores = {90, 85, 77};

// 方式三:完整写法
String[] names = new String[]{"Alice", "Bob"};

基本操作​

int[] nums = {10, 20, 30};

nums[0] = 99; // 修改元素
System.out.println(nums[1]); // 读取元素:20
System.out.println(nums.length); // 长度:3(注意:length 是属性,不是方法)

越界访问会抛出 ArrayIndexOutOfBoundsException,这是新手最常见的运行时异常之一。

遍历数组​

int[] nums = {1, 2, 3, 4, 5};

// 下标遍历:需要下标时使用
for (int i = 0; i < nums.length; i++) {
System.out.println(i + " -> " + nums[i]);
}

// 增强 for:只需要元素值时更简洁
for (int n : nums) {
System.out.println(n);
}

二维数组​

int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};

System.out.println(matrix[1][2]); // 6

for (int[] row : matrix) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}

Arrays 工具类​

java.util.Arrays 提供了常用的数组操作:

import java.util.Arrays;

int[] nums = {3, 1, 2};

Arrays.sort(nums); // 排序:[1, 2, 3]
int idx = Arrays.binarySearch(nums, 2); // 二分查找(需先排序):1
int[] copy = Arrays.copyOf(nums, 5); // 拷贝并指定新长度
String s = Arrays.toString(nums); // 转字符串:"[1, 2, 3]"