数组是一个固定大小、有序的集合,包含相同类型的元素,在内存中连续存储。数组是基础的,但由于其固定大小,对于动态集合,你通常更倾向于使用 ArrayList。
声明和创建数组
java
[] nums = [];
[] nums2 = {, , , , };
String[] names = [];
nums[] = ;
nums[];
nums.length;
数组的固定大小在创建时设定 — 你无法增长或缩小它们。元素默认为类型适当的零值(0、0.0、false、null)。
nums.length; // ✅ array — a field (no parentheses)
str.length(); // ✅ String — a method (parentheses)
list.size(); // ✅ collection — a method
数组的 length 是一个字段;String 的 length() 和集合的 size() 是方法 — 这是一个常见的混淆点。
int[] arr = {1, 2, 3};
arr[5]; // ❌ ArrayIndexOutOfBoundsException — Java checks bounds at runtime
Java 对越界访问抛出异常(不像 C,它会导致未定义行为) — 更安全,但你必须保持在 0 到 length-1 范围内。
// enhanced for-each (when you don't need the index)
for (int n : nums) {
System.out.println(n);
}
// traditional for (when you need the index)
for (int i = 0; i < nums.length; i++) {
nums[i] *= 2;
}
int[][] matrix = {{1, 2}, {3, 4}}; // array of arrays
matrix[0][1]; // 2
Array → fixed size, slightly faster, can hold primitives directly (int[])
ArrayList → DYNAMIC size (grow/shrink), rich methods (add/remove/contains),
but holds objects only (Integer, not int)
List<Integer> list = new ArrayList<>();
list.add(1); // grows dynamically — no fixed size
list.remove(0);
对于固定大小、性能敏感或原始数据,使用普通数组;当大小变化或需要便捷操作时,使用 ArrayList。
数组是 Java 中的基础数据结构 — 快速、内存高效、连续存储,直接使用,并且是许多集合的支撑(ArrayList 包装了一个数组)。
理解它们的固定大小特性、从 0 开始的索引、运行时边界检查、length 字段(与方法相对)陷阱,以及何时使用数组 vs ArrayList(固定/原始/快速 vs 动态/便捷)至关重要。
数组经常出现在算法和性能关键代码中,而了解它们的局限性(无法调整大小)解释了为什么动态集合存在,以及为什么它们通常更适合通用使用。