Arrays工具类(排序和查找)
该类提供了一个静态工厂使arrays可以当作lists。(This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.)
一、类声明 public class Array{…}
二、排序方法
(在…都用到了Arrays.sort)
public static void sort(int[] a) {
DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}
DualPivotQuicksort也是java.util中的一个工具类,并且声明为final不允许继承。merge sort中最大的数量设置为67,最大的长度设置为33。
此处调用6参数的方法static void sort(int[] a, int left, int right, int[] work, int workBase, int workLen){}
1、如果小于286个数的时候用该类中定义过的4参数quicksort方法sort(int[] a, int left, int right, boolean leftmost){}调用后结果直接返回。在4参数quicksort方法内部又分情形。
1)如果<47个数的时候用插入排序:如果要排序的是数组的最左边的位置,
如果不是
2)如果>=47个数用快速排序,取数组长度的7分之1长度作为seventh变量,取中间位置作为e3变量,最终求出e1、e2、e3、e4、e5五个位置将数组大致平均分为六份。然后分情况用快速排序递归调用4参数的sort();
三、查找方法
(对于有序数组的查找,不多说直接上代码"二分查找")
public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) {
rangeCheck(a.length, fromIndex, toIndex); //检查Index范围是否合法
return binarySearch0(a, fromIndex, toIndex, key);
}
// Like public version, but without range checks.
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1; //无符号右移1位,高位补0
int 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.
}
四、复制方法 Arrays.copyOf()
在ArrayList的构造方法、grow方法、clone方法都调用了elementData = Arrays.copyOf(elementData, size, Object[].class); 其中elementData声明为transient Object[] elementData;
Arrays.copyOf使用泛型声明了一个静态方法,会返回一份新的copy。源码如下:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength)); //调用了本地方法(JNI),用C语言实现底层
return copy;
}