The Java.util. Arrays class is a JDK utility class that handles various methods of Arrays, each of which is essentially static and can be called directly from the class name Arrays.

1, asList

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

Returns a list of fixed sizes supported by the specified array.

Note: The ArrayList returned by this method is not our usual collection class java.util.arrayList. The ArrayList is an inner class of Arrays Java. Util. Arrays. The ArrayList. This inner class has the following properties and methods:

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) {returnindexOf(o) ! = 1; }}Copy the code

The returned ArrayList is a fixed-length list that can only be viewed or modified, but cannot be added or deleted

This class does not have methods like add() or remove(). Methods corresponding to its parent class AbstractList will be called if operations are added or removed. And traceability of the parent class method will throw an UnsupportedOperationException anomalies. As follows:

 String[] str = {"a"."b"."c"};
 List<String> listStr = Arrays.asList(str);
 listStr.set(1, "e"); System.out.println(liststr.toString ())); //[a, e, c] listStr.add("a"); / / add elements complains Java. Lang. UnsupportedOperationExceptionCopy the code

The difference between an array of reference type and an array of primitive type

String[] str = {"a"."b"."c"}; List listStr = Arrays.asList(str); System.out.println(listStr.size()); //3 int[] I = {1,2,3}; List listI = Arrays.asList(i); System.out.println(listI.size()); / / 1Copy the code

The first result is liststr.size ()==3, and the second listi.size ()==1. Why is that?

Array. AsList (T… A). This method takes a mutable parameter, and the mutable parameter type is used as the parameter of the generic type. We know that primitive data types can’t be used as arguments to generics, but arrays are reference types, so arrays can be genericized, so int[] is the whole argument type, not int.

So generalizing the above method should be:

String[] str = {"a"."b"."c"}; List<String> listStr = Arrays.asList(str); System.out.println(listStr.size()); //3 int[] I = {1,2,3}; List<int[]> listI = Arrays.asList(i); Println (listi.size ()); listi.size (); listi.size (); //1 Integer[]in= {1, 2, 3}; List<Integer> listIn = Arrays.asList(in); Println (listin.size ()); system.out.println (listin.size ()); / / 3Copy the code

The elements in the returned ArrayList are references, not separate objects

String[] str = {"a"."b"."c"}; List<String> listStr = Arrays.asList(str); System.out.println(arrays.toString (STR)); //[a, b, c] listStr.set(0,"d"); System.out.println(arrays.toString (STR)); // Arrays.tostring (STR)); //[d, b, c]Copy the code

The arrays.tostring () method here prints the contents of the array, as we’ll see later. We’re changing the contents of the collection, the contents of the original array are also changing, so we’re passing in a reference type.

(4) How to obtain a List that can be added, deleted, changed, and checked?

 String[] str = {"a"."b"."c"};
 List<String> listStr = new ArrayList<>(Arrays.asList(str));
 listStr.add("d"); System.out.println(listStr.size()); / / 4Copy the code

We’ll explain the ArrayList collection class in more detail later, but you just need to know that it works.

⑤, Arrays.aslist () method usage scenarios

The Arrays utility class provides a method, asList, that converts a variable-length parameter or array to a List. However, the length of the generated List is fixed; The ability to modify operations (for example, to modify elements in a location); Cannot perform impact the length of the operation (such as the add and remove operations), otherwise it will throw an UnsupportedOperationException anomalies.

So arrays.asList is good for scenarios where you already have array data or elements, but you need to quickly build a List for reading without adding or deleting.

2, sort

The method is used to sort an array, in the Arrays class there are a series of overloaded methods, this method can the seven basic data types, including byte, char, double, float, int, long, short, etc can be sorted, There is also the Object type, which implements the Comparable interface, and the Comparator Comparator.

An array of primitive types

Int [] int[]

Int [] num =,3,8,5,2,4,6,7 {1}; Arrays.sort(num); System.out.println(Arrays.toString(num)); //[1, 2, 3, 4, 5, 6, 7, 8]Copy the code

Sort the array in ascending order by calling the sort(int[] a) method. Here we look at the source code is how to achieve the sort:

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

Call the DualPivotQuicksort.sort method inside the arrays.sort method. The source code of this method is very long, and it divides the array length by various algorithms, including quicksort, insertion sort, and bubble sort. See this blog post for the full source code.

Array of object types

The Comparable interface can be implemented to sort arrays of this type, overriding the compareTo method to sort.

 String[] str = {"a"."f"."c"."d"}; Arrays.sort(str); System.out.println(Arrays.toString(str)); //[a, c, d, f]Copy the code

The String type implements the Comparable interface, and the internal compareTo method compares by dictionary code.

Comparable if you do not implement the Comparable interface, you can implement sorting by using the Comparator

Person[] p = new Person[]{new Person("zhangsan",22),new Person("wangwu",11),new Person("lisi"33)}; Arrays.sort(p,new Comparator<Person>() { @Override public int compare(Person o1, Person o2) {if(o1 == null || o2 == null){
            return 0;
        }
        returno1.getPage()-o2.getPage(); }}); System.out.println(Arrays.toString(p));Copy the code

3, binarySearch

Use dichotomy to find an element in an array. This method, like the sort method, applies to a variety of primitive data types as well as objects.

Note: Dichotomy is lookup of sorted and ordered Arrays (for example, sorting with arrays.sort () and then calling this method for lookup). Returns the index if the element is found, -1 if not

Example:

Int [] num =,3,8,5,2,4,6,7 {1}; Arrays.sort(num); System.out.println(Arrays.toString(num)); //[1, 2, 3, 4, 5, 6, 7, 8] System.out.println(Arrays.binarySearch(num, 2)); // Returns the subscript 1 of the elementCopy the code

Specific source code implementation:

public static int binarySearch(int[] a, int key) {
        return binarySearch0(a, 0, a.length, key);
    }
    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]; // take the middle valueif (midVal < key)
            low = mid + 1;
            else if (midVal > key)
            high = mid - 1;
            else
            return mid; 
        }
        return -(low + 1); 
    }
Copy the code

4, copyOf

Copy an array element. The underlying implementation is system.arrayCopy (), which is a native method.

    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
Copy the code

SRC: the source array

SrcPos: The starting position from which the source array is copied

Dest: destination array

DestPos: indicates the starting position of the destination array

Length: indicates the replication length

Note: SRC and dest must both be arrays of the same type or of a transformable type.

Int [] num1 = {1, 2, 3}; int[] num2 = new int[3]; System.arraycopy(num1, 0, num2, 0, num1.length); System.out.println(Arrays.toString(num2)); / / [1, 2, 3]Copy the code
/** * @param original source array * @param newLength // Returns the length of new array * @return
     */
    public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
Copy the code

5. Equals and deepEquals

(1), equals

Equals is used to compare whether each element in the corresponding position in two arrays is equal.

Let’s look at the int array comparison source implementation:

public static boolean equals(int[] a, int[] a2) {
        if(a==a2)// Array references are equal, then the elements in them must be equalreturn true;
        if(a = = null | | a2 = = null)/one/two array is null, returnfalse
            return false;

        int length = a.length;
        if(a2.length ! = length)// The two arrays are not equal in lengthfalse
            return false;

        for(int i=0; i<length; / / by i++)forThe loop compares the equality of each element in the arrayif(a[i] ! = a2[i])return false;

        return true;
    }
Copy the code

Look at the comparison of object arrays:

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;
    }
Copy the code

It’s basically based on equals.

(2), deepEquals

It is also used to compare elements of two arrays for equality, but deepEquals can compare multi-dimensional arrays, nested arrays of any level.

         String[][] name1 = {{ "G"."a"."o"}, {"H"."u"."a"."n"}, {"j"."i"."e"}};  
         String[][] name2 = {{ "G"."a"."o"}, {"H"."u"."a"."n"}, {"j"."i"."e"}}; System.out.println(Arrays.equals(name1,name2)); //falseSystem.out.println(Arrays.deepEquals(name1,name2)); //true
Copy the code

6, the fill

This series of methods is used to assign values to arrays and can specify a range of values.

Public static void fill(int[] a, int val) {public static void fill(int[] a, int val) {for(int i = 0, len = a.length; i < len; i++) a[i] = val; } // Index fromIndex from fromIndex, Public static void fill(int[] a, int fromIndex, int toIndex, int val) {rangeCheck(a.length, fromIndex, toIndex); // Determine whether the range is reasonablefor (int i = fromIndex; i < toIndex; i++)
            a[i] = val;
    }
Copy the code

ToString and deepToString

ToString is used to print elements of a one-dimensional array, while deepToString is used to print elements of a multi-level nested array.

public static String toString(int[] 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(a[i]);
            if (i == iMax)
                return b.append('] ').toString();
            b.append(","); }}Copy the code

This series of tutorials will continue to be updated, you can search “IT Cola” on wechat to read the first time. Reply ebook has a selection of books that I have selected for you