The Arrays tools

Just like Collections, which provides special operations on or extensions to Collections, the Arrays class comes in the java.util package and contains methods for manipulating Arrays. In fact, we know that some other Set classes such as List and Set still provide many methods, but array does not belong to the collection system, it is identified by [], it does not provide users with any methods to operate, only provides a length attribute

If you look directly at this class, you’ll notice that it provides a lot of methods like this, but if you look closely, you’ll notice that many of these methods are overloaded, providing different methods for different types of arrays

Let’s take a look at some of the different approaches, and here are the main ones, and then we’ll talk about them

asList(T... a) 
binarySearch( Object[] a, Object key)
copyOf(Object[] original, int newLength) 
copyOfRange(Object[] original, int from, int to) 
deepEquals(Object[] a1, Object[] a2)
deepHashCode(Object a[]) 
deepToString(Object[] a) 
deepToString(Object[] a, StringBuilder buf, Set<Object[]> dejaVu) {
equals(Object[] a, Object[] a2)
fill(Object[] a, Object val)
hashCode(char a[])
legacyMergeSort(Object[] a) 
parallelPrefix(Object[] array, Object op)
parallelSetAll(Object[] array, IntToObjectFunction generator) 
parallelSort(Object[] a) 
setAll(Object[] array, IntToObjectFunction generator)
sort(Object[] a)
spliterator(Object[] array) 
spliterator(Object[] array, int startInclusive, int endExclusive)
stream(Object[] array)
stream(Object[] array, int startInclusive, int endExclusive) 
swap(Object[] x, int a, int b)
toString(Object[] a)
Copy the code

asList(T … a)

Convert an array or mutable argument to a List

Developers new to Java technology may not know that the Java language originally included arrays in response to performance criticisms from C++ developers in the early 1990s. We’ve come a long way since then, and arrays no longer offer performance advantages over the Java Collections library.

For example, to dump the contents of an array to a String, you iterate through the array and concatenate the contents into a String; The Collections implementation, on the other hand, has a toString() implementation available that can be used directly. With rare exceptions, it’s good practice to convert any array you encounter into a collection as soon as possible.

@Test
public void asList(a){
    List<String> list = Arrays.asList(new String[]{"a"."b"."c"});
    List<String> list2 = Arrays.asList("a"."b"."c");
    System.out.println(list);
    System.out.println(list2);
}
// Output the result
[a, b, c]
[a, b, c]
Copy the code

Note that the returned List cannot be modified, so if you try to add new elements will throw an UnsupportedOperationException.

Also, because arrays.aslist () uses mutable arguments to represent elements added to the List, it’s also easy to create lists of new objects.

sort()

Sort the elements of an array

Sort (Object[]) sorts all elements in ascending order

@Test
public void sort(a) {
    int[] nums = {2.5.0.4.6, -10};
    Arrays.sort(nums);
    for (int i : nums) {
        System.out.print(i + ""); }}// Output the result
-10 0 2 4 5 6 
Copy the code

Sort (Object[] array, int from, int to) Sort the elements in the specified range in ascending order

@Test
public void sort(a) {
    int[] nums = {2.5.0.4.6, -10};
    Arrays.sort(nums,0.4);
    for (int i : nums) {
        System.out.print(i + ""); }}// Output the result
0 2 4 5 6 -10 
Copy the code

Arrays.sort(nums, new Comparator()) uses the Comparator to specify the sort direction

ascending

@Test
public void sort(a) {
    Integer[] nums = {2.5.0.4.6, -10};
    Arrays.sort(nums, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            returno1.compareTo(o2); }});for (int i : nums) {
        System.out.print(i + ""); }}// Output the result
-10 0 2 4 5 6 
Copy the code

Descending order

@Test
public void sort(a) {
    Integer[] nums = {2.5.0.4.6, -10};
    Arrays.sort(nums, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            returno2.compareTo(o1); }});for (int i : nums) {
        System.out.print(i + ""); }}// Output the result
6 5 4 2 0 -10 
Copy the code

fill(Object[] a, Object val)

You can fill array elements with the same values

@Test
public void fill(a) {
    int[] nums = {2.5.0.4.6, -10};
    Arrays.fill(nums, 1);
    for (int i : nums) {
        System.out.print(i + ""); }}// Output the result
1 1 1 1 1 1
Copy the code

Array.fill (Object[] array,int from,int to,Object Object) fills the same value for all the elements in the specified range

@Test
public void fill(a) {
    int[] nums = {2.5.0.4.6, -10};
    Arrays.fill(nums, 1.3.100);
    for (int i : nums) {
        System.out.print(i + ""); }}// Output the result
2 100 100 4 6 -10 
Copy the code

toString(Object[] array)

Returns an array as a string, since the default output is the memory address

@Test
public void toStr(a) {
    int[] nums = {2.5.0.4.6, -10};
    System.out.println(nums);
    System.out.println(Arrays.toString(nums));
}
// Output the result
[I@587c290d
[2.5.0.4.6, -10]
Copy the code

deepToString(Object[][] arrays)

Returns the string form of a multidimensional array

@Test
public void deepToString(a) {
    int[][] nums = {{2.5.0.4.6, -10}, {2.5.0.4.6, -10}};
    System.out.println(nums);
    System.out.println(Arrays.deepToString(nums));
}
// Output the result
[[I@587c290d
[[2.5.0.4.6, -10], [2.5.0.4.6, -10]]
Copy the code

binarySearch(Object[] a, Object key)

Binary search is used to search for a particular key. If the index is found, -1 is returned. It is important to note that binary search requires the input to be ordered

Disordered input

@Test
public void binarySearch(a) {
    int bytes = Arrays.binarySearch(new byte[] {6.3.7.9.1.4.5.10},byte) 1);
    System.out.println(bytes);
}
// Output the result
-1
Copy the code

It can be seen that when our input is unordered, the search is not accurate. For example, the 1 above is present, but it is not found

Ordered input

@Test
public void binarySearch(a) {
    int bytes = Arrays.binarySearch(new byte[] {1.2.3.4.5.6.7},byte) 3);
    System.out.println(bytes);
}
// Output the result
2
Copy the code

copyOf(object[] original, int newLength)

Arraycopy copies an array to another array and returns the result. Let’s take a look at the implementation of this method. In fact, we can see the underlying implementation of this method by calling System

public static int[] copyOf(int[] original, int newLength) {
    int[] copy = new int[newLength];
  	Math.min(original.length, newLength) is the length to copy
    System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
    return copy;
}
Copy the code

NewLength refers to the length of the new array. If the length of the new array is greater than the length of the array to be copied, the empty position is filled by default

@Test
public void copyOf(a) {
    int[] ints = Arrays.copyOf(new int[] {1.2.3}, 10);
    System.out.println(Arrays.toString(ints)); 
}
// Output the result
[1.2.3.0.0.0.0.0.0.0]
Copy the code

If the length of the new array is smaller than the length of the old array, the corresponding data is copied

@Test
public void copyOf(a) {
    int[] ints = Arrays.copyOf(new int[] {1.2.3}, 10);
    System.out.println(Arrays.toString(ints));
    ints = Arrays.copyOf(new int[] {1.2.3}, 2);
    System.out.println(Arrays.toString(ints));
}
// Output the result
[1.2]
Copy the code

copyOfRange

Let’s look at the implementation of this method first, again with the help of System.arrayCopy

public static int[] copyOfRange(int[] original, int from, int to) {
    int newLength = to - from;
    if (newLength < 0)
        throw new IllegalArgumentException(from + ">" + to);
    int[] copy = new int[newLength];
  	// Specific ranges are implemented by math.min (original.length-from, newLength
    System.arraycopy(original, from, copy, 0,Math.min(original.length - from, newLength));
    return copy;
}
Copy the code
@Test
public void copyOfRange(a) {
    int[] ints = Arrays.copyOfRange(new int[] {9.8.7.6.5.4.3.2.1}, 0.5);
    System.out.println(Arrays.toString(ints));
}
// Output the result
[9.8.7.6.5]
Copy the code

parallelPrefix

The use of parallel computation, and the array to do the calculation of the function, because it is a functional interface, can be used as lambda expressions

@Test
public void parallelPrefix(a) {
    int[] ints = {1.2.3.4.5};
    //K represents the first value of the array (index 0), V represents the next value of K, and the values of the two indexes are added
    Arrays.parallelPrefix(ints,(K,V)-> K+V);
    // Output is [1, 3, 6, 10, 15] : the process is 1 and 2 add up to 3, 3 and 3 add up to 6, 6 and 4 add up to 10... And so on
    System.out.println(Arrays.toString(ints));

    int[] Ints = {5.4.3.2.1.0};
    // Add values from index 1 to index 5
    Arrays.parallelPrefix(Ints,1.5,(K,V) -> K + V);
    System.out.println(Arrays.toString(Ints)); // Output is [5, 4, 7, 9, 10, 0]

}
Copy the code

parallelSort

Sort the array using the parallel sort + merge sort algorithm *

@Test
public void parallelSort(a) {
    int[] ints = {2.3.4.5.1};
    Arrays.parallelSort(ints);
    // Output is: [1, 2, 3, 4, 5]
    System.out.println(Arrays.toString(ints));
    
    int[] Ints = {2.3.4.5.1.6.8.7};
    // Sort from index 1 to index 7
    Arrays.parallelSort(Ints,1.7);
    // Output is: [2, 1, 3, 4, 5, 6, 8, 7]
    System.out.println(Arrays.toString(Ints));
}
Copy the code

stream

Collections in Java provide a stream operation, but arrays do not, so a corresponding method is provided in this utility class, which we see was added in 1.8

/**
 * Returns a sequential {@link IntStream} with the specified array as its
 * source.
 *
 * @param array the array, assumed to be unmodified during use
 * @return an {@code IntStream} for the array
 * @since1.8 * /
public static IntStream stream(int[] array) {
    return stream(array, 0, array.length);
}
Copy the code
@Test
public void stream(a) {
    int[] ints = {1.2.3.4.5.6.7};
    IntStream stream = Arrays.stream(ints);
    // Call the stream count method to count the total number of data
    System.out.println(stream.count());

    // Count from index 0 to 3
    IntStream stre = Arrays.stream(ints, 0.3);
    System.out.println(stre.count());
}
Copy the code

conclusion

  1. Arraycopy is the underlying call to System. Arraycopy, so we can use the System. Arraycopy method as well as the two copy methods provided by the Arrays utility class
  2. List, Set and other collection classes in Java provide a lot of manipulation methods, but array it is not a collection system, it is through[]It does not provide the user with any method to operate on, only onelengthProperty, so the Arrays utility class provides a lot of ways to manipulate Arrays easily