Arrays工具类
- java.util.Arrays
- 操作数组的工具类,包含了用来操作数组(比如排序和搜索)的各种方法;
成员方法:(静态的)
- public static String toString(int[] a):返回指定数组内容的字符串表示形式;
- public static void sort(int[] a):对指定的int型数组按数字升序进行排序;
如果是数值,默认按照数字升序;如果是字符串,默认按照字母升序;如果是自定义的类型,那么这个自定义的类型需要有Comparable或者Comparator接口的支持; - public static int binarySearch(int[] a,int key):使用二分搜索法来搜索指定的int型数组,以获得指定的值;
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
// 定义一个数组
int[] arr = {24, 69, 80, 57, 13};
// 把数组转成字符串
System.out.println("排序前:" + Arrays.toString(arr)); // [24, 69, 80, 57, 13]
// 对数组进行排序
Arrays.sort(arr);
System.out.println("排序后:" + Arrays.toString(arr)); // [13, 24, 57, 69, 80]
// public static int binarySearch(int[] a,int key) 二分查找
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57)); // 2
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577)); // -6
}
}
源码解析:
public static void sort(int[] a) :底层是快速排序;
public static String toString(int[] a)
int[] arr = {24, 69, 80, 57, 13};
System.out.println("排序前:" + Arrays.toString(arr));
public static String toString(int[] a) {
//a -- arr -- {24, 69, 80, 57, 13}
if (a == null)
return "null"; //说明数组不存在
int iMax = a.length - 1;
if (iMax == -1)
return "[]"; //说明数组存在,但是没有元素
StringBuilder b = new StringBuilder();
b.append('['); //"["
for (int i = 0; ; i++) {
b.append(a[i]); //"[24, 69, 80, 57, 13"
if (i == iMax)
return b.append(']').toString(); //"[24, 69, 80, 57, 13]"
b.append(", "); //"[24, 69, 80, 57, "
}
}
public static int binarySearch(int[] a,int key)
int[] arr = {13, 24, 57, 69, 80};
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));
public static int binarySearch(int[] a, int key) {
//a -- arr -- {13, 24, 57, 69, 80} key -- 557
return binarySearch0(a, 0, a.length, key);
}
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
//a -- arr -- {13, 24, 57, 69, 80} fromIndex -- 0 toIndex -- 5 key -- 577
int low = fromIndex; //low = 0
int high = toIndex - 1; //high = 4
while (low <= high) {
int mid = (low + high) >>> 1; //mid=2, mid=3, mid=4
int midVal = a[mid]; //midVal=57, midVal=69, midVal=80
if (midVal < key)
low = mid + 1; //low=3, low=4, low=5
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found. //-6
}
案例:
(1)将一个随机字符串中的所有字符升序排列,并倒序打印;
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
String str = "asv76agfqwdfvasdfvjh";
// toCharArray:String --> 数组
char[] chars = str.toCharArray();
// 对字符数组进行升序排列
Arrays.sort(chars);
// 倒序遍历
for (int i = chars.length - 1; i >= 0; i--) {
System.out.print(chars[i]);
}
}
}