Arrays工具使用
package array;
import java.util.Arrays;
public class TestAyyays {
/**
* @Title: main
* @Description: TODO(Arrays使用)
* @param @param args 设定文件
* @return void 返回类型
* @throws
*/
public static void main(String[] args) {
// 定义一个数组
int[] arr = { 14, 29, 80, 87, 13 };
// public static String toString(int[] a) 把数组转成字符串
System.out.println("排序前:" + Arrays.toString(arr));
// public static void sort(int[] a) 对数组进行排序
Arrays.sort(arr);
System.out.println("排序后:" + Arrays.toString(arr));
// public static int binarySearch(int[] a,int key) 二分查找
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 87));
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 17));//不存在返回负数
}
}
源码分析
public static String toString(int[] a)
public static void sort(int[] a) 底层是快速排序
public static int binarySearch(int[] a,int key)
开发原则:只要是对象,我们就要判断该对象是否为null。
int[] arr = { 14, 29, 80, 87, 13 };
System.out.println("排序前:" + Arrays.toString(arr));
public static String toString(int[] a) {
if (a == null)
return "null"; //说明数组对象不存在
int iMax = a.length - 1; //iMax=4;
if (iMax == -1)
return "[]"; //说明数组存在,但是没有元素。
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
-----------------------------------------------------
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 17));
public static int binarySearch(int[] a, int key) {
//a -- arr -- { 14, 29, 80, 87, 13 }
//key -- 17
return binarySearch0(a, 0, a.length, key);
}
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
//a -- arr -- { 14, 29, 80, 87, 13 }
//fromIndex -- 0
//toIndex -- 5
//key -- 17
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];
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.
}