Arrays

来源:互联网 发布:网络海鲜吃播 编辑:程序博客网 时间:2024/06/05 08:23

位于*java.uti*l包下
该类提供了操纵数组的许多方法,其中的方法都能扔出NullPointerException。
api:https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

该类主要包含的方法:

  • asList----将数组转换为list返回
  • sort方法----排序
  • binarySearch----二分查找
  • copyOf----复制数组为某个长度
  • copyOfRange----将数组中的某段复制为一个新的数组
  • equals
  • fill
  • deepEquals
  • deepHashCode
  • deepToString
  • hashCode
  • toString

    除asList方法之外,其他方法都有多个重载方法。

asList

 public static <T> List<T> asList(T... a) {        return new ArrayList<>(a);    }

该方法返回一个固定长度的list,如果传入的参数为空会抛出NullPointerException。

sort

将数组进行升序排序。可以对整个数组排序,也可以定义排序范围。

 public static void sort(int[] a) {        DualPivotQuicksort.sort(a);    } public static void sort(int[] a, int fromIndex, int toIndex) {        rangeCheck(a.length, fromIndex, toIndex);        DualPivotQuicksort.sort(a, fromIndex, toIndex - 1);    }

binarySearch

Arrays还提供了二分查找的实现。

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;            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.    }
原创粉丝点击