Analysis and use of Arrays

Source: Internet
Author: User
Tags sorts
1. arrays class Introduction

The arrays class is a class provided by Java APIs. in the util package, this class contains various methods used to operate arrays, such as sorting and searching. In this class, if the specified array reference is null, such methods will throw nullpointerexception, this class also contains a static factory that allows you to view arrays as a list.

Arrays include sort, binarysearch, equals, fill, copyof, aslist, hashcode, deephashcode, deepequals, tostring, and deeptostring.Public MethodFor other classes. The methods inherited from Java. Lang. Object include clone, equals, finalize, getclass hashcode, y, policyall, tostring, and wait. The sort method is used for sorting. The binarysearch method is binary search, and the equals method is used for comparison. The fill method is used to fill a specific value in the array. copyof copies an array of a specific length, the aslist method is used to view arrays as a list.

The arrays class contains two private classes: The legacymergesort class and the arraylist class. gacmergesort is an old version of Merge Sorting implementation, and the arraylist is an array queue used to implement the aslist method.

Arrays Constructor

private Arrays() {}

We can see that the arrays constructor is set to private, indicating that this class is forbidden to use the default constructor and cannot be instantiated. However, you can use this class by providing static methods, this mode is the singleton mode.

Arrays method summary

public static void sort(Object[] a)public static void sort(Object[] a, int fromIndex, int toIndex)public static <T> void sort(T[] a, Comparator<? super T> c)public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)public static int binarySearch(Object[] a, Object key)public static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key)public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)public static boolean equals(Object[] a, Object[] a2)public static void fill(Object[] a, Object val)public static void fill(Object[] a, int fromIndex, int toIndex, Object val)public static <T> T[] copyOf(T[] original, int newLength)public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)public static <T> T[] copyOfRange(T[] original, int from, int to)public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)public static <T> List<T> asList(T... a)public static int hashCode(Object a[])public static int deepHashCode(Object a[])public static boolean deepEquals(Object[] a1, Object[] a2)public static String toString(Object[] a)public static String deepToString(Object[] a)
2. arrays source code analysis

Analyze the main methods in the arrays class based on the source code of jdk1.7.0 _ 45.

public static void sort(Object[] a) {        if (LegacyMergeSort.userRequested)            legacyMergeSort(a);        else            ComparableTimSort.sort(a);    }

This method sorts the array of specified objects in ascending order according to the natural order of the elements. When you do not request to use the Merge Sorting of earlier versions, you can directly use the comparabletimsort class method, the comparabletimsort class will be analyzed separately.

public static void sort(Object[] a, int fromIndex, int toIndex) {        if (LegacyMergeSort.userRequested)            legacyMergeSort(a, fromIndex, toIndex);        else            ComparableTimSort.sort(a, fromIndex, toIndex);    }

This method sorts the specified range of the specified object array in ascending order based on the natural order of the elements. Other implementations are the same as the preceding sorting method.

public static <T> void sort(T[] a, Comparator<? super T> c) {        if (LegacyMergeSort.userRequested)            legacyMergeSort(a, c);        else            TimSort.sort(a, c);    }

This method sorts the array of specified objects according to the sequence generated by the specified comparator. The specific sorting implementation is to call the sort method implementation of timsort.

public static <T> void sort(T[] a, int fromIndex, int toIndex,                                Comparator<? super T> c) {        if (LegacyMergeSort.userRequested)            legacyMergeSort(a, fromIndex, toIndex, c);        else            TimSort.sort(a, fromIndex, toIndex, c);    }

This method sorts the specified range of the specified object array according to the sequence generated by the specified comparator. The specific sorting implementation is to call the sort method implementation of timsort. The timsort class will be analyzed separately later.

 

public static int binarySearch(Object[] a, Object key) {        return binarySearch0(a, 0, a.length, key);}// Like public version, but without range checks.    private static int binarySearch0(Object[] a, int fromIndex, int toIndex,                                     Object key) {        int low = fromIndex;        int high = toIndex - 1;        while (low <= high) {            int mid = (low + high) >>> 1;            Comparable midVal = (Comparable)a[mid];            int cmp = midVal.compareTo(key);            if (cmp < 0)                low = mid + 1;            else if (cmp > 0)                high = mid - 1;            else                return mid; // key found        }        return -(low + 1);  // key not found.    }

This method uses the Binary Search Method to search for a specified array to obtain the specified object. The specific implementation of Binary Search does not perform the range check.

public static int binarySearch(Object[] a, int fromIndex, int toIndex,                                   Object key) {        rangeCheck(a.length, fromIndex, toIndex);        return binarySearch0(a, fromIndex, toIndex, key);}

This method uses the Binary Search Method to search for the range of the specified array to obtain the specified object.

public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {        return binarySearch0(a, 0, a.length, key, c);}// Like public version, but without range checks.    private static <T> int binarySearch0(T[] a, int fromIndex, int toIndex,                                         T key, Comparator<? super T> c) {        if (c == null) {            return binarySearch0(a, fromIndex, toIndex, key);        }        int low = fromIndex;        int high = toIndex - 1;        while (low <= high) {            int mid = (low + high) >>> 1;            T midVal = a[mid];            int cmp = c.compare(midVal, key);            if (cmp < 0)                low = mid + 1;            else if (cmp > 0)                high = mid - 1;            else                return mid; // key found        }        return -(low + 1);  // key not found.    }

The generic Implementation of binary search uses the Binary Search Method to search for a specified array to obtain the specified object.

public static <T> int binarySearch(T[] a, int fromIndex, int toIndex,                                       T key, Comparator<? super T> c) {        rangeCheck(a.length, fromIndex, toIndex);        return binarySearch0(a, fromIndex, toIndex, key, c);    }

The generic Implementation of binary search uses the Binary Search Method to search for the range of the specified array to obtain the specified object.

public static boolean equals(Object[] a, Object[] a2) {        if (a==a2)            return true;        if (a==null || a2==null)            return false;        int length = a.length;        if (a2.length != length)            return false;        for (int i=0; i<length; i++) {            Object o1 = a[i];            Object o2 = a2[i];            if (!(o1==null ? o2==null : o1.equals(o2)))                return false;        }        return true;    }

This method is used if two specified objects arrays belong to one another.Equal, ReturnsTrue. In the specific implementation, if one of the two objects is null, false is returned.

 

public static void fill(Object[] a, Object val) {        for (int i = 0, len = a.length; i < len; i++)            a[i] = val;    }

This method assigns the specified object reference to each element of the specified object array.

public static <T> T[] copyOf(T[] original, int newLength) {        return (T[]) copyOf(original, newLength, original.getClass());}public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {        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));        return copy;    }

Copy the specified array, intercept or fill it with null (if necessary), so that the copy has the specified length. Pay attention to the usage of generics ., Finally, the system. arraycopy function is called to perform the copy operation.

public static <T> T[] copyOfRange(T[] original, int from, int to) {        return copyOfRange(original, from, to, (Class<T[]>) original.getClass());}public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {        int newLength = to - from;        if (newLength < 0)            throw new IllegalArgumentException(from + " > " + to);        T[] copy = ((Object)newType == (Object)Object[].class)            ? (T[]) new Object[newLength]            : (T[]) Array.newInstance(newType.getComponentType(), newLength);        System.arraycopy(original, from, copy, 0,                         Math.min(original.length - from, newLength));        return copy;    }

Copy the specified range of the specified array to a new array.

@SafeVarargs    public static <T> List<T> asList(T... a) {        return new ArrayList<>(a);    }    /**     * @serial include     */    private static class ArrayList<E> extends AbstractList<E>        implements RandomAccess, java.io.Serializable    {        private static final long serialVersionUID = -2764017481108945198L;        private final E[] a;        ArrayList(E[] array) {            if (array==null)                throw new NullPointerException();            a = array;        }        public int size() {            return a.length;        }        public Object[] toArray() {            return a.clone();        }        public <T> T[] toArray(T[] a) {            int size = size();            if (a.length < size)                return Arrays.copyOf(this.a, size,                                     (Class<? extends T[]>) a.getClass());            System.arraycopy(this.a, 0, a, 0, size);            if (a.length > size)                a[size] = null;            return a;        }        public E get(int index) {            return a[index];        }        public E set(int index, E element) {            E oldValue = a[index];            a[index] = element;            return oldValue;        }        public int indexOf(Object o) {            if (o==null) {                for (int i=0; i<a.length; i++)                    if (a[i]==null)                        return i;            } else {                for (int i=0; i<a.length; i++)                    if (o.equals(a[i]))                        return i;            }            return -1;        }        public boolean contains(Object o) {            return indexOf(o) != -1;        }    }

Returns a list of fixed sizes supported by the specified array. @ Safevarargs: an example of how to suppress compiler warnings. It can only be used in methods or constructor with Variable Parameter lengths. The methods must be declared as static or final. Otherwise, a compilation error occurs. The premise for a method to use @ safevarargs annotation is that developers must ensure that the processing of generic parameters in the implementation of this method does not cause type security problems.

public static int hashCode(Object a[]) {        if (a == null)            return 0;        int result = 1;        for (Object element : a)            result = 31 * result + (element == null ? 0 : element.hashCode());        return result;    }

Returns a hash code based on the specified array. This method is inherited from Java. Lang. object.

public static int deepHashCode(Object a[]) {        if (a == null)            return 0;        int result = 1;        for (Object element : a) {            int elementHash = 0;            if (element instanceof Object[])                elementHash = deepHashCode((Object[]) element);            else if (element instanceof byte[])                elementHash = hashCode((byte[]) element);            else if (element instanceof short[])                elementHash = hashCode((short[]) element);            else if (element instanceof int[])                elementHash = hashCode((int[]) element);            else if (element instanceof long[])                elementHash = hashCode((long[]) element);            else if (element instanceof char[])                elementHash = hashCode((char[]) element);            else if (element instanceof float[])                elementHash = hashCode((float[]) element);            else if (element instanceof double[])                elementHash = hashCode((double[]) element);            else if (element instanceof boolean[])                elementHash = hashCode((boolean[]) element);            else if (element != null)                elementHash = element.hashCode();            result = 31 * result + elementHash;        }        return result;    }

Returns the hash code based on the "deep content" of the specified array.

public static boolean deepEquals(Object[] a1, Object[] a2) {        if (a1 == a2)            return true;        if (a1 == null || a2==null)            return false;        int length = a1.length;        if (a2.length != length)            return false;        for (int i = 0; i < length; i++) {            Object e1 = a1[i];            Object e2 = a2[i];            if (e1 == e2)                continue;            if (e1 == null)                return false;            // Figure out whether the two elements are equal            boolean eq = deepEquals0(e1, e2);            if (!eq)                return false;        }        return true;    }

If the two specified arrays areDeep equalityIs returned.True.

public static String toString(Object[] a) {        if (a == null)            return "null";        int iMax = a.length - 1;        if (iMax == -1)            return "[]";        StringBuilder b = new StringBuilder();        b.append(‘[‘);        for (int i = 0; ; i++) {            b.append(String.valueOf(a[i]));            if (i == iMax)                return b.append(‘]‘).toString();            b.append(", ");        }    }

Returns the string representation of the specified array.

public static String deepToString(Object[] a) {        if (a == null)            return "null";        int bufLen = 20 * a.length;        if (a.length != 0 && bufLen <= 0)            bufLen = Integer.MAX_VALUE;        StringBuilder buf = new StringBuilder(bufLen);        deepToString(a, buf, new HashSet<Object[]>());        return buf.toString();    }

Returns the string representation of the specified array "deep content.

3. Performance Analysis

......

4. Use of the arrays class

......

Analysis and use of Arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.