Java中的数组函数用法详解
1. Arrays.sort():对数组进行排序。
语法:public static void sort(int[] arr)
实例:
int[] arr = {10, 5, 6, 9, 4};
Arrays.sort(arr);
for (int i : arr) {
System.out.print(i + " "); // 输出:4 5 6 9 10
}
2. Arrays.binarySearch():在有序数组中进行二分查找。
语法:public static int binarySearch(int[] arr, int key)
实例:
int[] arr = {4, 5, 6, 9, 10};
int index = Arrays.binarySearch(arr, 6);
System.out.println(index); // 输出:2
3. Arrays.copyOf():复制数组并返回一个新的数组。
语法:public static int[] copyOf(int[] original, int newLength)
实例:
int[] arr = {1, 2, 3};
int[] newArr = Arrays.copyOf(arr, 5);
for (int i : newArr) {
System.out.print(i + " "); // 输出:1 2 3 0 0
}
4. Arrays.copyOfRange():复制数组的一部分并返回一个新的数组。
语法:public static int[] copyOf(int[] original, int from, int to)
实例:
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = Arrays.copyOfRange(arr, 2, 4);
for (int i : newArr) {
System.out.print(i + " "); // 输出:3 4
}
5. Arrays.fill():用指定的值填充整个数组。
语法:public static void fill(int[] a, int val)
实例:
int[] arr = new int[5];
Arrays.fill(arr, 9);
for (int i : arr) {
System.out.print(i + " "); // 输出:9 9 9 9 9
}
6. Arrays.equals():比较两个数组是否相等。
语法:public static boolean equals(int[] a, int[] b)
实例:
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(Arrays.equals(arr1, arr2)); // 输出:true
7. Arrays.asList():将数组转换成List。
语法:public static <T> List<T> asList(T... a)
实例:
Integer[] arr= {1, 2, 3};
List<Integer> list = Arrays.asList(arr);
System.out.println(list); // 输出:[1, 2, 3]
8. Arrays.stream():将数组转换成Stream对象。
语法:public static IntStream stream(int[] array)
实例:
int[] arr= {1, 2, 3};
IntStream stream = Arrays.stream(arr);
stream.forEach(i -> System.out.print(i + " ")); // 输出:1 2 3
9. Arrays.hashCode():返回数组的哈希码。
语法:public static int hashCode(int[] a)
实例:
int[] arr = {1, 2, 3};
System.out.println(Arrays.hashCode(arr)); // 输出:30817
10. Arrays.deepToString():以字符串形式返回多维数组。
语法:public static String deepToString(Object[] a)
实例:
int[][] arr = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(arr)); // 输出:[[1, 2], [3, 4]]
