Arrays 工具类

2023/11/21 技术

# 1.将数组元素拼接为带有格式的字符串

public static String toString (类型[] a)

package ArraysUse;

import java.util.Arrays;

public class ArraryTest {
    public static void main(String[] args) {
        int[]arr1 = {11, 22, 33, 44, 55};
        int[]arr2 = {66, 77, 88, 99, 100};
        System.out.println(Arrays.toString(arr1)); // [11, 22, 33, 44, 55]
    }
}
1
2
3
4
5
6
7
8
9
10
11

# 2.比较两个数组内容是否相同

pubilc static boolean equals (类型[] a, 类型[] b)

package ArraysUse;

import java.util.Arrays;

public class ArraryTest {
    public static void main(String[] args) {
        int[]arr1 = {11, 22, 33, 44, 55};
        int[]arr2 = {11, 22, 33, 44, 55}; 
        System.out.println(Arrays.toString(arr1)); // [11, 22, 33, 44, 55]
        System.out.println(Arrays.equals(arr1, arr2)); // true

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
package ArraysUse;

import java.util.Arrays;

public class ArraryTest {
    public static void main(String[] args) {
        int[]arr1 = {11, 22, 33, 44, 55};
        int[]arr2 = {11, 22, 33, 44, 66};
        System.out.println(Arrays.toString(arr1)); // [11, 22, 33, 44, 55]
        System.out.println(Arrays.equals(arr1, arr2)); // false

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3.查找元素在数组中的索引(二分查找法:保证数组的元素是排序好的)

public static int binarySearch (int []a, int key)

package ArraysUse;

import java.util.Arrays;

public class ArraryTest {
    public static void main(String[] args) {
        int[] arr1 = {11, 22, 33, 44, 55};
        int[] arr2 = {11, 22, 33, 44, 66};
        System.out.println(Arrays.binarySearch(arr1, 33)); // 2
    }
}
1
2
3
4
5
6
7
8
9
10
11

如果查找的元素,在数组中不存在:返回(-(插入点) - 1)

列如 int [] arr1 = {11, 22, 33, 44, 55}

向数组中插入一个元素的索引就是插入点

查找出来的结果就是((-5 )-1) = -6

System.out.println(Arrays.binarySearch(arr1, 66)); // -6
1

如果乱序的情况下

int[]nums = {22, 11, 33, 66, 88};
System.out.println(Arrays.binarySearch(nums, 2)); // -1
1
2

# 4.数组排序

Arrays.sort(nums);
System.out.println(Arrays.toString(nums)); // [11, 22, 33, 66, 88]
// TODO: 代办的事宜
/**
  * TODO:代办的事宜
  */
1
2
3
4
5
6
LOSER
米津玄師