The Java.util.Arrays class is a dedicated utility class for Arrays, and the Java.util.

How do I know the author’s name? Look at the source code can, friends, loaded force bar)

What does Arrays do? Common ones are:

  • Create an array
  • To compare an array
  • Sort an array
  • An array of retrieval
  • An array of transferring
  • Print the array
  • Array to the List
  • setAll
  • ParallelPrefix (parallelPrefix)

That next, the friends are not eager to fight with the second brother to advance. Leave you.

Create an array

There are three ways to create Arrays using the Arrays class:

  • CopyOf, copies the specified array, intercepts or fills it with null
  • CopyOfRange, copies the specified range of arrays into a new array
  • Fill, to fill the array

1) copyOf:

String[] intro = new String[] { "Heavy"."Silent"."The king"."二" };
String[] revised = Arrays.copyOf(intro, 3);
String[] expanded = Arrays.copyOf(intro, 5);
System.out.println(Arrays.toString(revised));
System.out.println(Arrays.toString(expanded));
Copy the code

Revised and expanded are copied new arrays of length 3 and 5, respectively, specifying an array length of 4. Take a look at the output:

[sink, silent, king, two, null]Copy the code

See yet? So I cut the last digit because it’s 3; Expanded fills the bits with null because the length is 5.

2) copyOfRange:

String[] intro = new String[] { "Heavy"."Silent"."The king"."二" };
String[] abridgement = Arrays.copyOfRange(intro, 0.3);
System.out.println(Arrays.toString(abridgement));
Copy the code

The copyOfRange() method takes three arguments, the first to the specified array, the second to the start position (included), and the third to the end position (not included). Take a look at the output:

[Shen, Silence, Wang]Copy the code

The position of 0 is “sink” and the position of 3 is “two”, which means that the array elements are intercepted from 0 bits (inclusive) to 3 bits (inclusive). So what happens if we say that the index exceeds the length of the array?

String[] abridgementExpanded = Arrays.copyOfRange(intro, 0.6);
System.out.println(Arrays.toString(abridgementExpanded));
Copy the code

The end position is 6, exceeding the specified array length by 4.

[Sink, silent, king, two, null, null]Copy the code

Null is still used for padding. Why do you do that? Think about it for a moment. I think the author took into account the problem that Arrays are out of bounds. Otherwise, every time you call the Arrays class, you have to judge the length for many times.

3) Fill in

String[] stutter = new String[4];
Arrays.fill(stutter, "Silent King II.");
System.out.println(Arrays.toString(stutter));
Copy the code

Use the new keyword to create an array of length 4, then use the fill() method to fill the four positions as “Silent King two”, and look at the output:

[Silent King 2, Silent King 2, Silent King 2, Silent King 2]Copy the code

If you want an array with identical elements, the fill() method comes in handy.

02. Compare arrays

The Equals () method of the Arrays class checks whether two Arrays are equal, as shown in the following example:

String[] intro = new String[] { "Heavy"."Silent"."The king"."二" };
boolean result = Arrays.equals(new String[] { "Heavy"."Silent"."The king"."二" }, intro);
System.out.println(result);
boolean result1 = Arrays.equals(new String[] { "Heavy"."Silent"."The king"."Three" }, intro);
System.out.println(result1);
Copy the code

The following output is displayed:

true
false
Copy the code

Result = true, result1 = false

Take a quick look at the source code for equals() :

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++) {
        if(! Objects.equals(a[i], a2[i]))return false;
    }

    return true;
}
Copy the code

The array is an object, so use the “==” operator to check whether the array is null if it is not equal. If both values are null, return false. If length is not equal, return false; Otherwise, call objects.equals () in turn to compare whether elements in the same position are equal.

Feel very rigorous, this is the meaning of learning source code, appreciation at the same time, learning.

In addition to the equals() method, there is another trick to determining whether two arrays are equal, although there is a (very small) chance of error. That’s the arrays.hashcode () method.

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

The hash algorithm itself is very rigorous, so if two arrays have the same hash value, you can almost say that two arrays are equal.

String[] intro = new String[] { "Heavy"."Silent"."The king"."二" };

System.out.println(Arrays.hashCode(intro));
System.out.println(Arrays.hashCode(new String[] { "Heavy"."Silent"."The king"."二" }));
Copy the code

Take a look at the output:

868681617, 868681617,Copy the code

The hashes of both arrays are equal, after all, the elements are the same. But this is really not rigorous enough. Use objects.equals () in preference.

03, Array sort

The sort() method of the Arrays class is used to determine whether two Arrays are equal, as in this example:

String[] intro1 = new String[] { "chen"."mo"."wang"."er" };
String[] sorted = Arrays.copyOf(intro1, 4);
Arrays.sort(sorted);
System.out.println(Arrays.toString(sorted));
Copy the code

Since sorting changes the original array, we make a new copy using the copyOf() method. Take a look at the output:

[chen, er, mo, wang]
Copy the code

As you can see, they are arranged in ascending order of the first letter. Basic data types are sorted by biaxial quicksort, and reference data types are sorted by TimSort, using techniques from Peter McIlroy’s “Optimistic Sorting and Information Theory Complexity”.

04. Array retrieval

Once sorted, you can use the binarySearch() method of the Arrays class for binary lookup. Otherwise, only linear retrieval, the efficiency will be much lower.

String[] intro1 = new String[] { "chen"."mo"."wang"."er" };
String[] sorted = Arrays.copyOf(intro1, 4);
Arrays.sort(sorted);
int exact = Arrays.binarySearch(sorted, "wang");
System.out.println(exact);
int caseInsensitive = Arrays.binarySearch(sorted, "Wang", String::compareToIgnoreCase);
System.out.println(caseInsensitive);
Copy the code

The binarySearch() method can be either precise or fuzzy, such as ignoring case. Take a look at the output:

3
3
Copy the code

The sorted result is [Chen, ER, Mo, Wang], so the retrieved subscript is 3.

05, array flow

Stream is very powerful. If you need to get started, check out an article I wrote earlier:

This article introduces you to Java Stream streams, too strong

The stream() method of the Arrays class converts Arrays to streams:

String[] intro = new String[] { "Heavy"."Silent"."The king"."二" };
System.out.println(Arrays.stream(intro).count());
Copy the code

You can also specify a starting and ending subscript for the stream() method:

System.out.println(Arrays.stream(intro, 1.2).count());
Copy the code

If the subscript range is wrong, such as end from 2 to 1, the program will be thrown ArrayIndexOutOfBoundsException exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: origin(2) > fence(1)
	at java.base/java.util.Spliterators.checkFromToBounds(Spliterators.java:387)
Copy the code

06. Print arrays

I previously wrote a separate article about how arrays are printed:

What’s the most elegant way to print a Java array?

Println = system.out.println = system.out.println = system.out.println = system.out.println = system.out.println

[Ljava.lang.String;@3d075dc0
Copy the code

Arrays.tostring () : Arrays.tostring ()

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(","); }}Copy the code

Small partners can enjoy this section of source code, feeling very thoughtful.

07, Array to List

As powerful as arrays are, there are few utility methods they can manipulate by themselves, such as determining whether an array contains a value. It’s a lot easier to convert to List.

String[] intro = new String[] { "Heavy"."Silent"."The king"."二" };
List<String> rets = Arrays.asList(intro);
System.out.println(rets.contains("二"));
Copy the code

But it is important to note that the Arrays. AsList () returns the Java. Util. Arrays. The ArrayList, not Java. Util. ArrayList, its length is fixed, delete or add to elements.

rets.add("Three");
rets.remove("二");
Copy the code

When these two methods are executed, an exception is thrown:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.add(AbstractList.java:153)
	at java.base/java.util.AbstractList.add(AbstractList.java:111)
Copy the code

To manipulate elements, one more step is required:

List<String> rets1 = new ArrayList<>(Arrays.asList(intro));
rets1.add("Three");
rets1.remove("二");
Copy the code

08, setAll

Java 8 added the setAll() method, which provides a functional programming entry for populating array elements:

int[] array = new int[10];
Arrays.setAll(array, i -> i * 10);
System.out.println(Arrays.toString(array));
Copy the code

So what does this code mean? I equals the index of the array, starting at 0 and ending at 9, so I * 10 means starting at 0 * 10 and ending at 9 * 10. Look at the output:

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Copy the code

Much more powerful than the previous fill() method, right? The same elements are no longer filled in.

09, parallelPrefix

The parallelPrefix() method, like the setAll() method, also provided after Java 8, provides a functional programming portal to manipulate the element at the current subscript position with the element before it by iterating through the elements in the array. The result of the operation then overwrites the element at the current subscript position.

int[] arr = new int[] { 1.2.3.4};
Arrays.parallelPrefix(arr, (left, right) -> left + right);
System.out.println(Arrays.toString(arr));
Copy the code

Lambda (left, right) -> left + right); Lambda (left, right) -> left + right

Lambda expression primer, this is enough

To make it easier for you to see, let’s modify the above code slightly:

int[] arr = new int[] {1.2.3.4};
Arrays.parallelPrefix(arr, (left, right) -> {
    System.out.println(left + "," + right);
    return left + right;
});
System.out.println(Arrays.toString(arr));
Copy the code

Let’s take a look at the output:

1, 2, 3, 3, 6, 4Copy the code

That is, the Lambda expression executes three times:

  • The first time you add 1 and 2, you get 3, and you replace the 1
  • The second one is the sum of 3 and 3, and you get 6, which is the sum of the first one plus the element with subscript 2
  • And then the third time I add 6 and 4, I get 10, which is the result of the second time plus the element with subscript 3

Kind of powerful, right?

10 and summarize

Well, my dear friends, that’s all the content of this article, can see here are the best programmers, brother must give you a thumbs up.

I am silent King 2, an interesting programmer. If you think this article is helpful to you, please search “Silent King ii” on wechat and read it for the first time. Reply [666] there is also a 500G HIGH-DEFINITION teaching video (classified) that I prepared for you.

Interview on GitHub

Original is not easy, do not want a free ticket, please point a praise for this article, it will be the strongest power FOR me to write more high-quality articles.