Arrays类包含了:排序、查找、填充、打印内容等常见的操作。
打印
import java.util.Arrays;
public class TestArrays {
public static void main(String[] args) {
int[] a = {100,20,35,4,78};
System.out.println(a);
System.out.println(Arrays.toString(a));
}
}
结果是:
[I@15db9742
[100, 20, 35, 4, 78]
查看Arrays.toString()源码:
public static String toString(int[] a) {
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]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
帮助我们打印数组中的内容,其中
return b.append(']').toString();
toString()
方法是StringBuilder
中重写的方法,返回一个String类型
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
排序
Arrays.sort(a);
System.out.println(Arrays.toString(a));
通过查看sort
源码发现使用的是快速排序思想,3k多行的代码慢慢看。
/**
* Sorts the specified array into ascending numerical order.
*
* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
* offers O(n log(n)) performance on many data sets that cause other
* quicksorts to degrade to quadratic performance, and is typically
* faster than traditional (one-pivot) Quicksort implementations.
*
* @param a the array to be sorted
*/
public static void sort(int[] a) {
DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}
二分查找
使用Arrays
类中的binarySearch
方法进行二分查找,查询api手册可知:
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int []) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
也就是说在使用二分查找前必须要进行排序!
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a, 100));
查看binarySearch
源码:
public static int binarySearch(int[] a, int key) {
return binarySearch0(a, 0, a.length, key);
}
private static int binarySearch0(short[] a, int fromIndex, int toIndex,
short key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
short midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
此处不是很懂,为什么要用
int mid = (low + high) >>> 1;
而不是
int mid = low + ((high - low) >>> 1)
难道不怕溢出吗??