Java Arrays工具类解析(Java 8-17)

一、Arrays工具类概述

java.util.Arrays是Java集合框架中提供的数组操作工具类,包含各种静态方法用于操作数组(排序、搜索、比较、填充、复制等)。自Java 8到17版本,Arrays类不断增强了功能,特别是引入了并行操作和Stream支持。

二、基础操作(Java 8+)

1. 数组打印

int[] numbers = {3, 1, 4, 1, 5, 9};
System.out.println(Arrays.toString(numbers)); 
// 输出: [3, 1, 4, 1, 5, 9]

int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(matrix));
// 输出: [[1, 2], [3, 4]]

2. 数组比较

int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(Arrays.equals(arr1, arr2)); // true

String[][] strs1 = {{"A", "B"}, {"C"}};
String[][] strs2 = {{"A", "B"}, {"C"}};
System.out.println(Arrays.deepEquals(strs1, strs2)); // true

3. 数组填充

int[] nums = new int[5];
Arrays.fill(nums, 1);       // [1, 1, 1, 1, 1]
Arrays.fill(nums, 1, 3, 9); // [1, 9, 9, 1, 1] (范围左闭右开)

4. 数组复制

int[] original = {1, 2, 3, 4, 5};
int[] copy1 = Arrays.copyOf(original, 3);    // [1, 2, 3]
int[] copy2 = Arrays.copyOfRange(original, 1, 4); // [2, 3, 4]

三、排序与搜索(Java 8+)

1. 数组排序

int[] numbers = {3, 1, 4, 1, 5, 9};

// 全数组排序
Arrays.sort(numbers); // [1, 1, 3, 4, 5, 9]

// 范围排序
Arrays.sort(numbers, 1, 4); // [1, 1, 3, 4, 5, 9]

// 并行排序(大数据量性能更好)
Arrays.parallelSort(numbers);

2. 自定义排序

String[] words = {"apple", "Banana", "cherry"};

// 按字母顺序(区分大小写)
Arrays.sort(words); // ["Banana", "apple", "cherry"]

// 不区分大小写排序
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER); 
// ["apple", "Banana", "cherry"]

// 使用Comparator
Arrays.sort(words, Comparator.comparing(String::length).reversed());
// ["Banana", "cherry", "apple"]

3. 二分查找

int[] sorted = {1, 3, 5, 7, 9};
int index = Arrays.binarySearch(sorted, 5); // 2
int notFound = Arrays.binarySearch(sorted, 6); // -4 (插入点为3,返回-3-1)

四、Java 8新增功能

1. Stream支持

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

// 转换为IntStream
Arrays.stream(nums)
      .filter(n -> n % 2 == 0)
      .forEach(System.out::println); // 2, 4

// 指定范围
Arrays.stream(nums, 1, 4).forEach(System.out::println); // 2, 3, 4

2. parallelPrefix(并行前缀计算)

int[] nums = {1, 2, 3, 4};
Arrays.parallelPrefix(nums, (a, b) -> a + b);
System.out.println(Arrays.toString(nums)); // [1, 3, 6, 10]

3. setAll与parallelSetAll

int[] squares = new int[5];
Arrays.setAll(squares, i -> i * i); // [0, 1, 4, 9, 16]

// 并行版本
Arrays.parallelSetAll(squares, i -> i * i * i); // [0, 1, 8, 27, 64]

五、Java 9新增功能

1. equals比较增强

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, 0, 2, b, 0, 2)); // true (比较范围)

2. mismatch方法

int[] a = {1, 2, 3, 4};
int[] b = {1, 2, 4, 4};
int index = Arrays.mismatch(a, b); // 2 (第一个不匹配的索引)

六、Java 11新增功能

1. compare和compareUnsigned

int[] a = {1, 2, 3};
int[] b = {1, 3, 2};
int result = Arrays.compare(a, b); // 负数(a < b)

byte[] bytes1 = {(byte) 0xFF, 0x00};
byte[] bytes2 = {0x7F, 0x00};
int unsigned = Arrays.compareUnsigned(bytes1, bytes2); // 正数(无符号比较)

七、Java 17新增功能

1. arraySize计算

Object array = new int[10];
int size = Arrays.arraySize(array); // 10

2. arrayIndexScale

Object intArray = new int[10];
Object longArray = new long[10];
System.out.println(Arrays.arrayIndexScale(intArray)); // 4 (int占4字节)
System.out.println(Arrays.arrayIndexScale(longArray)); // 8 (long占8字节)

八、多维数组操作

1. 多维数组排序

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

// 按每行第一个元素排序
Arrays.sort(matrix, Comparator.comparingInt(a -> a[0]));
// [[1, 2], [3, 4], [5, 0]]

// 按每行第二个元素排序
Arrays.sort(matrix, Comparator.comparingInt(a -> a[1]));
// [[5, 0], [1, 2], [3, 4]]

2. 不规则数组处理

String[][] irregular = {{"A", "B"}, {"C"}, {"D", "E", "F"}};

// 深度操作依然有效
System.out.println(Arrays.deepToString(irregular));
// [[A, B], [C], [D, E, F]]

九、性能优化技巧

1. 选择合适的排序方法

// 小数组(<1万元素)
Arrays.sort(array);

// 大数组(>1万元素)
Arrays.parallelSort(array);

2. 避免不必要的数组复制

// 不好的做法
int[] copy = Arrays.copyOf(original, original.length);
Arrays.sort(copy);

// 好的做法(直接操作原数组)
Arrays.sort(original);

3. 使用setAll初始化大型数组

// 比循环更简洁高效
int[] largeArray = new int[100_000];
Arrays.setAll(largeArray, i -> i * 2);

十、高级应用案例

1. 自定义对象数组操作

class Person {
    String name;
    int age;
    // 构造方法/getter/setter省略
}

Person[] people = {
    new Person("Alice", 25),
    new Person("Bob", 20),
    new Person("Charlie", 30)
};

// 按年龄排序
Arrays.sort(people, Comparator.comparingInt(p -> p.age));

// 使用Stream处理
Arrays.stream(people)
      .filter(p -> p.age > 22)
      .map(Person::getName)
      .forEach(System.out::println);

2. 数组与集合转换

String[] names = {"Alice", "Bob", "Charlie"};

// 数组转List(注意:返回的是不可变List)
List<String> list = Arrays.asList(names);

// Java 8 Stream转换
List<String> mutableList = Arrays.stream(names)
                                .collect(Collectors.toList());

// List转数组
String[] array = list.toArray(new String[0]);

3. 科学计算应用

double[] data = new double[10000];
Arrays.setAll(data, i -> Math.random());

// 计算平均值
double avg = Arrays.stream(data).average().orElse(0);

// 并行计算标准差
double mean = avg;
double variance = Arrays.stream(data)
                       .parallel()
                       .map(d -> Math.pow(d - mean, 2))
                       .average()
                       .orElse(0);
double stdDev = Math.sqrt(variance);

十一、常见问题与解决方案

1. Arrays.asList()的陷阱

Integer[] intArray = {1, 2, 3};
List<Integer> list = Arrays.asList(intArray);

// 以下操作会抛出UnsupportedOperationException
// list.add(4); 
// list.remove(0);

// 解决方案:新建ArrayList
List<Integer> mutableList = new ArrayList<>(Arrays.asList(intArray));

2. 多维数组比较

int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{1, 2}, {3, 4}};

// 错误做法
System.out.println(Arrays.equals(a, b)); // false

// 正确做法
System.out.println(Arrays.deepEquals(a, b)); // true

3. 并行操作注意事项

int[] data = new int[1000000];

// 并行操作需要确保操作是无状态的
Arrays.parallelSetAll(data, i -> {
    // 不要使用外部变量,确保线程安全
    return i * i;
});

十二、版本特性总结

Java版本新增重要方法
8stream(), parallelSort(), parallelPrefix(), setAll()
9equals()范围比较, mismatch()
11compare(), compareUnsigned()
17arraySize(), arrayIndexScale()

通过掌握Arrays工具类的这些功能,您可以高效地处理各种数组操作,从简单的排序搜索到复杂的并行计算。根据不同的Java版本选择合适的方法,能够显著提升代码的简洁性和性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值