Java 8增强的工具类 Arrays(二)

时间:2021-11-12 19:26:32

一、排序方法:

5.1void sort(type[] a)

作用:给数组a排序

5.2void sort(type[] a,int fromIndex,int toIndex)

作用:给数组a指定的范围排序

5.3、源码:

public static void sort(byte[] a) {

        DualPivotQuicksort.sort(a);

}

 

public static void sort(byte[] a, int fromIndex, int toIndex) {

        rangeCheck(a.length, fromIndex, toIndex);

        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);

}

 

 public static void sort(byte[] a, int left, int right) {

        // Use counting sort on large arrays

        if (right - left > COUNTING_SORT_THRESHOLD_FOR_BYTE) {

            int[] count = new int[NUM_BYTE_VALUES];

 

            for (int i = left - 1; ++i <= right;

                count[a[i] - Byte.MIN_VALUE]++

            );

            for (int i = NUM_BYTE_VALUES, k = right + 1; k > left; ) {

                while (count[--i] == 0);

                byte value = (byte) (i + Byte.MIN_VALUE);

                int s = count[i];

 

                do {

                    a[--k] = value;

                } while (--s > 0);

            }

        } else { // Use insertion sort on small arrays

            for (int i = left, j = i; i < right; j = ++i) {

                byte ai = a[i + 1];

                while (ai < a[j]) {

                    a[j + 1] = a[j];

                    if (j-- == left) {

                        break;

                    }

                }

                a[j + 1] = ai;

            }

        }

}

 

二、转换方法:

6.1void parallelSort(type[] a)

6.2void parallelSort(type[] a,int fromIndex,int toIndex)

作用:这两个方法和sort方法相同,只不过增加并行能力,可以利用多CPU并行来提高性能。(Java 8中增加的新功能)

6.3XXXStream stream(xxx[] array)

6.4XXXStream stream(xxx[] array,int fromIndex,int toIndex)

作用:将数组转换为StreamStreamJava 8新增的流式编程的API

 

总结:Arrays类中的static方法很多,在Java 8中新增了很多支持并行的方法,随着现代PC和服务机的硬件发展,java提供更多人性化的功能。