四、数组常用操作(实战技巧)
1. 数组排序
使用Arrays.sort()方法(默认升序),支持基本类型和引用类型数组:
import java.util.Arrays;
public class ArraySort {
public static void main(String[] args) {
// 基本类型数组排序
int[] nums = {3, 1, 4, 1, 5, 9};
Arrays.sort(nums); // 升序排序
System.out.println("升序排序后:" + Arrays.toString(nums)); // 输出:[1, 1, 3, 4, 5, 9]
// 引用类型数组排序(String默认按字典序)
String[] names = {"Li", "Zhang", "Wang", "Zhao"};
Arrays.sort(names);
System.out.println("字典序排序后:" + Arrays.toString(names)); // 输出:[Li, Wang, Zhang, Zhao]
// 自定义降序排序(Java 8+)
Integer[] integers = {3, 1, 4, 1, 5, 9};
Arrays.sort(integers, (a, b) -> b - a); // 降序
System.out.println("降序排序后:" + Arrays.toString(integers)); // 输出:[9, 5, 4, 3, 1, 1]
}
}
2. 数组查找
使用Arrays.binarySearch()方法实现二分查找(必须先排序,否则结果不准确):
import java.util.Arrays;
public class ArraySearch {
public static void main(String[] args) {
int[] nums = {2, 5, 8, 12, 16};
int target = 8;
// 二分查找(数组必须已排序)
int index = Arrays.binarySearch(nums, target);
if (index >= 0) {
System.out.println("目标元素" + target + "在索引" + index); // 输出:目标元素8在索引2
} else {
System.out.println("目标元素未找到");
}
}
}
3. 数组复制
常用两种方式:Arrays.copyOf()(指定新长度)和System.arraycopy()(高效复制部分元素):
import java.util.Arrays;
public class ArrayCopy {
public static void main(String[] args) {
int[] original = {10, 20, 30, 40};
// 方式1:Arrays.copyOf(原数组, 新长度)
int[] copy1 = Arrays.copyOf(original, 3); // 复制前3个元素
System.out.println("copy1:" + Arrays.toString(copy1)); // 输出:[10, 20, 30]
int[] copy2 = Arrays.copyOf(original, 5); // 新长度大于原数组,补默认值0
System.out.println("copy2:" + Arrays.toString(copy2)); // 输出:[10, 20, 30, 40, 0]
// 方式2:System.arraycopy(原数组, 原起始索引, 目标数组, 目标起始索引, 复制长度)
int[] copy3 = new int[4];
System.arraycopy(original, 1, copy3, 0, 3); // 从original索引1开始,复制3个元素到copy3索引0
System.out.println("copy3:" + Arrays.toString(copy3)); // 输出:[20, 30, 40, 0]
}
}
4. 数组转字符串(便于打印)
使用Arrays.toString()方法(避免手动遍历打印):
import java.util.Arrays;
public class ArrayToString {
public static void main(String[] args) {
String[] fruits = {"苹果", "香蕉", "橙子"};
System.out.println(Arrays.toString(fruits)); // 输出:[苹果, 香蕉, 橙子]
// 二维数组转字符串用Arrays.deepToString()
int[][] matrix = {{1,2}, {3,4}};
System.out.println(Arrays.deepToString(matrix)); // 输出:[[1, 2], [3, 4]]
}
}
五、数组实战案例
案例 1:计算数组元素的总和与平均值
public class ArraySumAvg {
public static void main(String[] args) {
int[] scores = {85, 92, 78, 95, 88};
int sum = 0;
// 计算总和
for (int score : scores) {
sum += score;
}
// 计算平均值(注意强转避免整数除法)
double avg = (double) sum / scores.length;
System.out.println("总和:" + sum); // 输出:438
System.out.println("平均值:" + avg); // 输出:87.6
}
}
案例 2:查找数组中的最大值和最小值
public class ArrayMaxMin {
public static void main(String[] args) {
int[] nums = {3, 1, 4, 1, 5, 9, 2, 6};
int max = nums[0]; // 假设第一个元素是最大值
int min = nums[0]; // 假设第一个元素是最小值
for (int num : nums) {
if (num > max) {
max = num; // 更新最大值
}
if (num < min) {
min = num; // 更新最小值
}
}
System.out.println("最大值:" + max); // 输出:9
System.out.println("最小值:" + min); // 输出:1
}
}
案例 3:数组去重(保留第一个出现的元素)
import java.util.Arrays;
public class ArrayDeduplication {
public static void main(String[] args) {
int[] original = {1, 2, 2, 3, 3, 3, 4};
int[] result = new int[original.length];
int index = 0; // 结果数组的索引
// 遍历原数组,去重
for (int num : original) {
boolean isDuplicate = false;
// 检查当前元素是否已在结果数组中
for (int i = 0; i < index; i++) {
if (result[i] == num) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
result[index++] = num;
}
}
// 截取有效长度(去除末尾默认值)
int[] finalResult = Arrays.copyOf(result, index);
System.out.println("去重后:" + Arrays.toString(finalResult)); // 输出:[1, 2, 3, 4]
}
}
六、常见误区与避坑指南
1. 索引越界异常(ArrayIndexOutOfBoundsException)
- 原因:访问索引超出
0 ~ 数组长度-1范围; - 解决:遍历用
i < 数组.length(而非i <= 数组.length),避免硬编码索引。
2. 空指针异常(NullPointerException)
-
原因:数组未初始化(仅声明未赋值,数组名为
null)或引用类型数组元素为null; -
示例:
String[] names; System.out.println(names[0]); // 报错:NullPointerException(数组未初始化) String[] arr = new String[3]; System.out.println(arr[0].length()); // 报错:NullPointerException(元素为null) -
解决:先初始化数组,引用类型元素使用前先判空。
3. 数组长度不可修改
- 误区:认为
数组.length = 新长度可以修改数组长度; - 事实:数组长度是只读属性,一旦创建无法修改;
- 解决:需扩容时,创建新数组并复制原数组元素(如
Arrays.copyOf())。
4. 整数除法导致精度丢失
- 误区:计算平均值时直接用
sum / 数组.length(整数除法会舍弃小数); - 解决:将其中一个操作数强转为
double,如(double) sum / 数组.length。
七、总结
Java 数组是处理批量相同类型数据的基础工具,核心要点总结:
- 数组是引用类型,需初始化(静态 / 动态)后才能使用,长度固定;
- 一维数组重点掌握声明、初始化、遍历(for/for-each)和常用操作(排序、查找、复制);
- 二维数组是 “数组的数组”,遍历需嵌套循环;
- 避免索引越界、空指针异常,注意整数除法精度问题;
- 结合实战场景(求和、求最值、去重)灵活运用数组操作。
掌握数组后,你将能高效处理批量数据,为后续学习集合(List、Map)、数据结构(栈、队列)等内容打下坚实基础。在实际开发中,若需动态长度或更灵活的操作,可使用ArrayList等集合类,但数组仍是性能优先场景的首选。