Arrays源码分析
简介
Arrays.class中是对array进行操作的类,主要的操作包括排序和搜索。如果array的引用为空,则会抛出空指针异常
NullPointerException
方法
1.rangeCheck 数组越界检查
private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
if (fromIndex > toIndex)
{
throw new IllegalArgumentException(
"fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
}
if (fromIndex < 0)
{
throw new ArrayIndexOutOfBoundsException(fromIndex);
}
if (toIndex > arrayLength)
{
throw new ArrayIndexOutOfBoundsException(toIndex);
}
}
私有的静态方法。
2.排序
在Arrays.java中,对基本类型的数组提供了DualPivotQuicksort即双轴快速排序。
主要是提供了sort方法和其重载:
public static void sort(int[] a) {
DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}
#重载
public static void sort(int[] a, int fromIndex, int toIndex) {
rangeCheck(a.length, fromIndex, toIndex);
DualPivotQuicksort.sort(a, fromIndex, toIndex - 1, null, 0, 0);
}
除了int之外,还可以对char、shot、long、double、byte、float运行此方法。改变待排序数组即可。
还提供parallelSort的排序方式,处理的基本类型同上。
/*
算法思想:
并行排序的思想就是将数组划分成几个小数组并行排序然后合并
*/
public static void parallelSort(int[] a) {
int n = a.length, p, g;
if (n <= MIN_ARRAY_SORT_GRAN ||
(p = ForkJoinPool.getCommonPoolParallelism()) == 1)
DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
else
new ArraysParallelSortHelpers.FJInt.Sorter
(null, a, new int[n], 0, n, 0,
((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
MIN_ARRAY_SORT_GRAN : g).invoke();
}
注意:
-
MIN_ARRAY_SORT_GRAN官方文档中称为粒度,其实可以理解为待排序数组的允许最小长度,如果低于这个长度或者线程为1则直接调用双轴快排DualPivotQuicksort,对应的就是这段代码:
if (n <= MIN_ARRAY_SORT_GRAN || (p = ForkJoinPool.getCommonPoolParallelism()) == 1) DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);
-
当满足长度要求之后,实际上是调用了Helper类,完成的并行排序算法。
-
ArraysParallelSortHelpers简要源码分析
-
此类是帮助Arrays.parallelSort完成其排序操作的实际操作类。那么Helper为每个基本类型都提供了静态类,每个静态类负责完成Sorter和Merger。
-
基本算法思想:
-
if array size is small, just use a sequential quicksort (via Arrays.sort)</
-