In the daily use of Java array process, will often use some expansion, sort, search and other operations.

Arrays APi

To prepare

Create an integer array: int [] ints = new int [],4,2,3,5,6,1,5 {3};

The sorting

Arrays.sort(ints);  // Internal sort
System.out.println(Arrays.toString(ints));  //[1, 2, 3, 3, 4, 5, 5, 6]

Copy the code

copy

ints = Arrays.copyOf(ints, ints.length + 1);  / / capacity
ints[ints.length - 1] = 7;
System.out.println("Arrays.toString(ints) = " + Arrays.toString(ints)); // [1, 2, 3, 3, 4, 5, 5, 6, 7] increases the capacity

Copy the code

Binary search

If it exists, return a random index. If it does not exist, return the negative value after the index + 1 corresponding to the low pointer of the search result. The source code is as follows:

private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;  // toIndex is not included in the search content

        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.
    }

Copy the code

Use code:

System.out.println("Arrays.binarySearch(ints, 2) = " + Arrays.binarySearch(ints, 2)); // Arrays.binarySearch(ints, 2) = 1
int i = Arrays.binarySearch(ints, 8); // Not found -(low + 1);
System.out.println(i); // Return - (9 + 1) = -10;

Copy the code

Fill in default values

In some cases, we want the initial value of an array to be custom, so we can use the fill function to do that. Note that we can only operate on a one-dimensional array; if it is a two-dimensional array, then treat it as if it were an array, using a layer of loop, and then fill each array with a custom value.

Arrays.fill(ints2, 2); // Fill in the default values
System.out.println("Arrays.toString(ints2) = " + Arrays.toString(ints2));

Copy the code

Compare two arrays for equality

You can also use the equals method that comes with Arrays, but it’s recommended that you use arrays.equals () for comparison.

int[] ints2 = new int[] {1.2.3};
        System.out.println("Arrays.equals(ints, ints2) = " + Arrays.equals(ints, ints2));  // false to determine whether two arrays are equal.

Copy the code

Convert an array to a List

List

Integer = arrays.aslist (1, 2, 3, 4);

This method can be used, but the generated List is an inner class, not an ArrayList under java.utils. You cannot add, delete, or delete the List.

List

collect = Arrays.stream(ints).boxed().collect(arrays.tolist ());

The result is a normal List, and you can do a series of operations on the stream after the stream is generated. This approach is highly recommended

Classification: Java

Tags:Java