Arrays
?Arrays是Java中一個非常實用的工具類,位于java.util包下。它提供了一系列靜態(tài)方法,用于操作數(shù)組,例如排序、搜索、比較、填充、復(fù)制等。
Arrays類的常用方法
- 排序
sort(int[] a):對指定的 int 類型數(shù)組按升序進行排序。
?int[] arr = {5, 3, 8, 1, 2};
?Arrays.sort(arr);
sort(T[] a, int fromIndex, int toIndex):對指定數(shù)組的指定范圍按升序進行排序,fromIndex 是起始索引(包含),toIndex 是結(jié)束索引(不包含)。
?int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5};
//3 1 1 4 5 9 2 6 5
?Arrays.sort(arr, 2, 5);
sort(T[] a, Comparator<? super T> c):對指定對象數(shù)組根據(jù)指定比較器進行排序。
?Person[] people = {
??new Person("Alice", 25),
??new Person("Bob", 20),
??new Person("Charlie", 30)
?};
?//指定age字段進行升序排序
?Arrays.sort(people, Comparator.comparingInt(p -> p.age));
parallelSort(int[] a):對指定的 int 類型數(shù)組進行并行排序,在多核處理器上可以提高排序性能。
?int[] arr = {5, 3, 8, 1, 2};
?//1 2 3 5 8
?Arrays.parallelSort(arr);- 復(fù)制方法
copyOf(int[] original, int newLength):復(fù)制指定的int類型數(shù)組,截取或用0填充(如果需要),以使副本具有指定的長度。
?int[] original = {1, 2, 3};
?int[] copy = Arrays.copyOf(original, 5);
copyOfRange(int[] original, int fromIndex, int toIndex ):復(fù)制指定的int類型數(shù)組,fromIndex是起始索引(包含),toIndex 是結(jié)束索引(不包含)。
?int[] original = {1, 2, 3, 4, 5, 6, 7, 8, 9};
? // 復(fù)制索引2到5(不包含索引5)的元素
?int[] copy = Arrays.copyOfRange(original, 2, 5);
與之相對System有個類似的方法System.arraycopy。
?int[] original = {1, 2, 3, 4, 5};
?int[] destination = new int[3];
?// 從original數(shù)組的索引1開始復(fù)制,復(fù)制2個元素,從destination數(shù)組的索引0位置開始
?System.arraycopy(original, 1, destination, 0, 2);- 搜索方法
binarySearch(int[] a, int key):使用二分搜索法在指定的int類型數(shù)組中搜索指定的值。數(shù)組必須是已排序的,否則結(jié)果不確定。
?int[] arr = {1, 3, 5, 7, 9};
?int key = 5;
?//2
?int index = Arrays.binarySearch(arr, key);- 填充方法
fill(int[] a, int val):將指定的 int 類型值填充到指定的int類型數(shù)組的每個元素中。
?int[] arr = new int[5];
?//10 10 10 10 10
?Arrays.fill(arr, 10);- 比較方法
equals(int[] a, int[] a2):比較兩個 int 類型數(shù)組是否相等。如果兩個數(shù)組包含相同數(shù)量的元素,并且對應(yīng)位置的元素也相等,則認為這兩個數(shù)組相等。
?int[] arr1 = {1, 2, 3};
?int[] arr2 = {1, 2, 3};
?//true,arr2 = {1, 3, 2};就是false
?boolean isEqual = Arrays.equals(arr1, arr2);- 轉(zhuǎn)換為字符串方法
toString(int[] a):返回指定數(shù)組內(nèi)容的字符串表示形式。
?int[] arr = {1, 2, 3};
?String str = Arrays.toString(arr);