java.util.Arrays

By | 4月 20, 2015

Arrays class contains many methods used to manipulate array ( like sort methods and binary search method). When the input parameter is null, it will throw runtime NullPointerException.

 

1. public static <T> List<T> asList(T… a)

To convert array as List, the return type is java.util.Arrays$ArrayList which is different from java.util.ArrayList. We can’t convert Arrays$ArrayList into java.util.ArrayList. In fact, Arrays$ArrayList is a static inner class of java.util.ArrayList:

private static class ArrayList<E> extends AbstractList<E>

 

2. binarySearch() method

The input array should be sorted, otherwise the return value will not be correct. Use binary search algorithm to find the certain key value’s position and return the value’s index, return -1 if not found.

· public static int binarySearch(T[] a, T key), return key’s index in array a,return -1 if not found。

· public static int binarySearch(T[] a, int fromIndex, int toIndex, T key), search key in array a from fromIndex to toIndex and return the index, return -1 if not found.

 

3. copyOf() method

· public static T[] copyOf (T[] original, int newLength)

— create a new array with the specified length (newLength). If newLength is lesser than original array’s length, some element will lost. If newLength is greater than original array’s length, the surplus elements’ value is default value of each type (int type is 0, Boolean type is false …)

 

4. copyOfRange() method

· public static T[] copyOfRange (T[] original, int from, int to)

— create a new array using original array’s value within the range [from, to). Parameter ‘from’ >= 0 and parameter ‘to’ >= from. Parameter ‘from’ can be greater than original array’s length, which means surplus elements’ value is the default value of each type.

 

5. toString() method

· public static String toString (T[] a), convert array a to String in format like “[value1, value2, value3 …]”

 

6. sort() method

· public static void sort (T[] a), sorts the specified array into ascending numerical order.

· public static void sort (T[] a, int fromIndex, int toIndex), sorts the specified range of the array into ascending numerical order

· public static void sort (T[] a, Comparator<? super T> c),

Use indicated comparator to sort input array a.

· public static void srot (T[] a, int fromIndex, int toIndex, Comparator<? super T> c),

Use indicated comparator to sort the specified range of the array.

 

7. fill() method

· public static void fill (T[] a, T val), fill each element with val.

· public static void fill (T[] a, int fromIndex, int toIndex, T val), assigns the specified value ‘val’ to each element of the input array a.

 

8. equals() method

· public static Boolean equals (T[] a, T[] a2), return true only if a and a2 contain the same elements in the same order.

 

9. hashCode() method

· public static int hasCode (T[] a), returns a hash code based on the contends of the specified array.