Java array of useful features java.util.Arrays

Three kinds of initialization method

public class test {
    static int[] returnIntarray() {
        return new int[] {1,2,3};// Dynamic aggregate initialization
    }
    static void receiveIntarray(int [] pa){}
    
    public static void main(String[] args) {
        Integer[] a;//声明了,但没初始化
        Integer[] b = new Integer[5];//平常的初始化
        for(int i = 0; i < b.length; i++)
            if(b[i] == null) // Can test for null reference
                b[i] = Integer.valueOf(i);
        // Aggregate initialization:
        Integer[] d = { Integer.valueOf(1),
                Integer.valueOf(2), Integer.valueOf(3),
        };
        // Dynamic aggregate initialization:
        a = new Integer[]{
            Integer.valueOf(1), Integer.valueOf(1),
        };

        receiveIntarray( new int[]{1,2,3} );
    }
}
  • Integer[] aI declare an array of references, but not initialized.
  • Integer[] b = new Integer[5]This is the usual array initialization way, pay attention to the numbers in parentheses are a must. With the new keyword also explains the reference object is an array of objects that exist in the heap, but an array of objects we use. This embodiment will initialize a default value for each array element, since a reference type Integer, the default value is null; if int[] f = new int[5]then the default value is the default value of 0 int itself.
  • Integer[] d = { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), }This is an aggregate initialization, can only be used in an array of objects declared in the statement, for example here.
  • a = new Integer[]{ Integer.valueOf(1), Integer.valueOf(1), }This dynamic aggregate initialization, compared with the strip, this can occur (not only the declaration statement, but also as a reference to assign herein, or in the return statement assigned anywhere in the array return new int[] {1,2,3}, is passed to the parameter type or a method for the array as the argument receiveIntarray( new int[]{1,2,3} ))
  • Note that the initialization gathered inside the element, followed by the last element can also have a comma.
  • Note, Integer b[] = new Integer[5]also can be compiled, but such people can not declare variables glance variable of type b Integer[], it is strongly not recommended to write.

Multidimensional Arrays

import java.util.Arrays;

public class test {
    public static void main(String[] args) {
        int[][] a = new int[2][3];
        int[][] b = {
                {1, 2, 3},
                {4, 5, 6}
        };
        int[][] c = new int[][]{
                {1, 2, 3},
                {4, 5, 6}
        };
        System.out.println(Arrays.deepToString(a));
        System.out.println(Arrays.deepToString(b));
        System.out.println(Arrays.deepToString(c));
    }
}/*output:
[[0, 0, 0], [0, 0, 0]]
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
*/

There are three ways to initialize the above example to create a two-dimensional array. Arrays.deepToString()Static methods designed to print multidimensional arrays.

Rough array

An array is rough, multidimensional arrays, the same level of sub-arrays, length can be different. Professional said: each vector in the matrix array configuration may have any length. C ++ there should be no rough array.

public class test {
    public static void main(String[] args) {
        int[][] c = new int[][]{
                {1},
                {2, 3},
                {4, 5, 6},
        };
    }
}

Example initialized using the aggregated manner can easily initialize a coarse array.

//: arrays/RaggedArray.java
import java.util.*;

public class RaggedArray {
    public static void main(String[] args) {
        Random rand = new Random(47);
        // 3-D array with varied-length vectors:
        int[][][] a = new int[rand.nextInt(7)][][];
        System.out.println(Arrays.deepToString(a));
        for(int i = 0; i < a.length; i++) {
            a[i] = new int[rand.nextInt(5)][];
            //System.out.println(Arrays.deepToString(a));//单独取消此注释以更好地观察赋值的过程
            for(int j = 0; j < a[i].length; j++)
                a[i][j] = new int[rand.nextInt(5)];
            //System.out.println(Arrays.deepToString(a));//单独取消此注释以更好地观察赋值的过程
        }
        System.out.println(Arrays.deepToString(a));
    }
} /* Output:
[null, null, null, null, null, null]
[[], [[0], [0], [0, 0, 0, 0]], [[], [0, 0], [0, 0]], [[0, 0, 0], [0], [0, 0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0], []], [[0], [], [0]]]
*///:~
  • Above example int[][][] a = new int[rand.nextInt(7)][][]that the normal initialization mode, but in order to achieve the effect of coarse array initialization specify only the size of the first dimension, the second dimension and size as soon as the third dimension is determined during initialization, it is impossible to be rough array a. Of course, the size of the first dimension of a multidimensional array must be determined, or will be error, one-dimensional array, too.
  • The results from the printing [null, null, null, null, null, null]point of view, int[][][] a = new int[rand.nextInt(7)][][]to the first dimension size 6, but each element (two-dimensional array) are null, it need be described for aeach element assignment.
  • Inside the loop a[i] = new int[rand.nextInt(5)][]when the assignment to the two-dimensional array, the first dimension is to determine only the size, the size of the random number is used, in the end for the coarse array.
  • In circulation a[i][j] = new int[rand.nextInt(5)]to a one-dimensional array assignment when, but also the size of the random number used. Up to this point, the size of the third dimension was only OK.

java.util.Arrays practical function

This chapter may not use to talk, to see more interesting source code and comments it.

System.arraycopy()

This function is used to copy the array. Notes basic reading the source code to understand, and under what circumstances Throws also told you.

    /* @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     * @exception  IndexOutOfBoundsException  if copying would cause
     *               access of data outside array bounds.
     * @exception  ArrayStoreException  if an element in the <code>src</code>
     *               array could not be stored into the <code>dest</code> array
     *               because of a type mismatch.
     * @exception  NullPointerException if either <code>src</code> or
     *               <code>dest</code> is <code>null</code>.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

Src is copied from the start position of the source array srcPos length elements past, destPos copied to the target position array to dest destPos + length-1 position.

Otherwise, if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • The src argument and dest argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.

As described above, the element type two component type array must be the exact same type, even if the automatic entry box where not so that, even if an array element of type int, the other is Integer, will be given ArrayStoreException.
Also note that, if the element type of the array reference component type is a reference type, so just copy a reference to the past, that a copy of references to an object did not happen.

equals()

This function compares two arrays are the same, simply, when only between two arrays have the same elements, and the order of the elements of both the same, it returns true. This function of all 基本类型[]and Object[]is overloaded, so we can guarantee can be performed on all arrays.

    public static boolean equals(int[] a, int[] 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++)
            if (a[i] != a2[i])
                return false;

        return true;
    }
  • if (a==a2) return true;Here are null, then the direct return true if two references point to the same array, or two references.
  • if (a==null || a2==null) return false;If there is only a is null, then return false.
  • The remaining logic in turn is determined length, the length of the same, it is sequentially determined whether each of the same elements.

However, double[]heavy-duty version of equals () a bit different:

        for (int i=0; i<length; i++)
            if (Double.doubleToLongBits(a[i])!=Double.doubleToLongBits(a2[i]))
                return false;

Two doubles d1 and d2 are considered equal if:

new Double(d1).equals(new Double(d2))
(Unlike the == operator, this method considers NaN equals to itself, and 0.0d unequal to -0.0d.)

Note that the stresses are equal two double, with the equals method of packaging Double judged. Double equals method and ==operation are not the same, because System.out.println(Double.NaN==Double.NaN)it returns false, System.out.println(0.0d == -0.0d)returns true. But the source or use of Double.doubleToLongBits (should be equals method and this method is equivalent to Double in comparative terms), consider floating point numbers are real underlying IEEE floating point representation , then this method is the underlying bit pattern converting floating point numbers into a long and compare.

float[]Heavy-duty version of equals () Similarly:

        for (int i=0; i<length; i++)
            if (Float.floatToIntBits(a[i])!=Float.floatToIntBits(a2[i]))
                return false;

Object[]Overloaded version of equals () represents a reference type, the logic is slightly different, since, unlike the basic type reference types, which may be null:

        for (int i=0; i<length; i++) {
            Object o1 = a[i];
            Object o2 = a2[i];
            if (!(o1==null ? o2==null : o1.equals(o2)))//先判断二者是否都为null
                return false;
        }

The reason, do not put a few heavy-duty versions of the equals () written in a generic way, I think it is because although generic method type parameters can be inferred, but because of type erasure at runtime is not to get specific type, and thus, not depending on the particular type of treatment for various (front is mentioned several different logical overloaded version).

sort()

Calls Arrays.sort()divided into three cases:

  • Array element is a reference type, and the element type implements the Comparableinterface.
  • Array element is a reference type, but the element type does not implement Comparablethe interface. The second parameter is required to achieve Comparator<T>, when T is inherited Comparator array element is designated as the type or parent type.
  • Array elements as the basic type. All basic types have been overloaded version.
  • Reference type called sequencing implementation must be stable sort.
  • Arrays.parallelSort()It is divided into three cases.

[1] array element is a reference type, and the element type implements the Comparableinterface.

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

For the above method and reference types, add the System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");phrase, the system will call the previous merge sort legacyMergeSort (but this is the sort achieved will be removed in a future version, so caution), otherwise the system call ComparableTimSort.sort.
Calling this method requires the array element type implements Comparable interface, because the code that implements these two sort of the array elements will turn into a strong Comparable to compare.

[2] array element is a reference type, but the element type does not implement Comparablethe interface.

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

public interface Comparator<T> {
    int compare(T o1, T o2);
    //省略
}    

This version does not require the elements implement the Comparable interface, because very often, the array elements it is impossible to implement the Comparable interface. You need to realize Comparator generic interface, when implement this interface, so that the type parameter T is the array element type can be. Note that reference types Comparator<? super T>so that ca reference entry code can only use a generic (i.e., only "write", belongs to the method just compare "write"); and Comparator type parameter T may be the parent class, Comparator accept more flexible.

[3] as the basic array element type.

    public static void sort(int[] a) {
        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
    }

There are also basic types, such as heavy-duty int[]version, where the call is DualPivotQuicksort.sort, other types of basic version also call this sort. Because the basic type does not require stability, so with fast row.

binarySearch()

Before calling the binary search, you must ensure that the array has been ordered, otherwise return undefined. If you key in the array has a plurality of, we can not guarantee to find which key.
Basic types [1]. (There are other basic types of heavy-duty version)

public static int binarySearch(long[] a, long key) {
        return binarySearch0(a, 0, a.length, key);
    }

@param a the array to be searched @param key the value to be searched for @return index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

If the key does not exist in the array will be returned . Inserted into the insertion point, meaning that the parameters should be placed in the index key , the original and index element and move back after the elements. The insertion point is to represent the key should be on what position the array. It will be the first element is greater than the index key; or the possible index values, when all the elements are less than key.(-(insertion point) - 1)insertion pointinsertion pointa.length

[2] reference type and array element implements the Comparable interface.

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

[3] reference type, and array elements do not implement the Comparable interface. Another parameter Comparator interface.

    public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) {
        return binarySearch0(a, 0, a.length, key, c);
    }
Published 171 original articles · won praise 130 · views 280 000 +

Guess you like

Origin blog.csdn.net/anlian523/article/details/102636995