Java utility class: Arrays
The Arrays class is an array manipulation class defined in the java.util package. Its main functions are finding array elements, filling and sorting array contents, etc
1. Sort the array by sort
Key: Sort the elements of an array from smallest to largest by default.
The arguments to this method can be arrays of both the underlying data types and object references. You can also specify the index range of the elements in the array to be sorted.
When sorting objects, all elements in the array must implement the Comparable interface. (Pretend you didn’t see it, haha)
That is, all elements in the array must be comparable to each other (that is, e1.compareTo(e2) must not throw ClassCastException for any E1 and E2 elements in the array)
(1) Numerical sorting
Sorting rules: Sort from smallest to largest
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest01 {
public static void main(String[] args) {
int[] a = {9.8.7.2.3.4.1.0.6.5};
Arrays.sort(a);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}Copy the code
(2) String sorting
Sorting rules: uppercase first, then lowercase
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest02 {
public static void main(String[] args) {
String[] a = {"a"."A"."b"."B"};
Arrays.sort(a);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}Copy the code
(3) Strict sorting of strings
Sorting rules: Insensitive sort strictly alphabetically (insensitive sort)
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest03 {
public static void main(String[] args) {
String[] a = {"a"."C"."b"."D"};
Arrays.sort(a,String.CASE_INSENSITIVE_ORDER);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}Copy the code
(4) Reverse ordering
Sorting rules: lowercase first uppercase
String reversal
package com.shxt.demo03;
import java.util.Arrays;
import java.util.Collections;
public class ArraysTest04 {
public static void main(String[] args) {
String[] a = {"a"."A"."b"."B"};
Arrays.sort(a, Collections.reverseOrder());//Collections Utility classes in the collection class
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}Copy the code
For numeric sorting, use wrapper classes
package com.shxt.demo03;
import java.util.Arrays;
import java.util.Collections;
public class ArraysTest05 {
public static void main(String[] args) {
// Basic data types cannot be used
Integer[] a = {9.8.7.2.3.4.1.0.6.5};
Arrays.sort(a, Collections.reverseOrder());
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}Copy the code
We used the Collections utility class. If we want to define our rules ourselves, we need to use the comparator interface Comparable.
package com.shxt.demo03;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysTest05_1 {
public static void main(String[] args) {
// Basic data types cannot be used
Integer[] a = {9.8.7.2.3.4.1.0.6.5};
Arrays.sort(a, new IntegerComparator());
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}/** * Comparator is an interface * so our own IntegerComparator class here requires implents instead of extends Comparator ** /
class IntegerComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
// If o1 is less than o2, we return a positive value; if n1 is greater than n2, we return a negative value.
// Reverse the order
if(o1 < o2) {
return 1;
}else if(o1 > o2) {
return -1;
}else {
return 0; }}}Copy the code
(5) Ignore case reverse sort
package com.shxt.demo03;
import java.util.Arrays;
import java.util.Collections;
public class ArraysTest04 {
public static void main(String[] args) {
String[] a = {"a"."C"."b"."D"};
Arrays.sort(a, Collections.reverseOrder());
Collections.reverse(Arrays.asList(a));// Ignore it for now
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + "\t"); }}}Copy the code
(6) Interval sorting – Understand
Arrays.sort(int[] a, int fromIndex, int toIndex)
Copy the code
Sort fromIndex to toindex-1; sort fromIndex to toindex-1;
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest07 {
public static void main(String[] args) {
int[] a = {9.8.7.2.3.4.1.0.6.5};
Arrays.sort(a, 0.3);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + ""); }}}7 8 9 2 3 4 1 0 6 5
Copy the code
One of the most common mistakes made by Java beginners is trying to write methods to sort arrays,
In fact, the array sort function, in the Java API has been implemented, we do not need to repeat the wheel.
If you are a fresh graduates, still need to learn all kinds of sort, refer to the website: http://geek.csdn.net/news/detail/113928
ParallelSort parallelSort is a new sort API in Java8 that allows you to sort in parallel. ParallelSort uses the Fork/Join framework of Java7 to enable sorting tasks to be performed by multiple threads in the thread pool. Fork/Join implements a task stealing algorithm that allows one idle thread to steal other threads' idle tasks for processing. The more obvious the advantages of parallelSort become.Copy the code
2. The binarySearch method for finding arrays
public static int binarySearch(T[] a, T key)
Copy the code
Uses binary search to search an array of the specified type for the specified value.
[Important] The array must be sorted (via the sort() method) before this call can be made.
If the array is not sorted, the result is indeterminate. If an array contains more than one element with a specified value, there is no guarantee which one is found.
Return value description:
1. If the keyword is found, the return value is the index of the keyword’s position in the array, starting at 0
2. If the keyword is not found, the insertion point value is negative. The insertion point value is the index of the position of the first element in the array that is larger than the keyword.
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest08 {
public static void main(String[] args) {
int[] b = new int[] {4.25.10.95.06.21};
System.out.println("The original array is:");
for (int dim1 : b) {
System.out.print("" + dim1 + "");
}
// Always sort first
Arrays.sort(b);
System.out.println("After sorting:");
for (int x : b) {
System.out.print(x + "");
}
System.out.println();
int index = Arrays.binarySearch(b, 2);
System.out.println(The return value for keyword 2 is: + index);
index = Arrays.binarySearch(b, 20);
System.out.println(The return value for keyword 20 is: + index);
index = Arrays.binarySearch(b, 30);
System.out.println("The return value of keyword 30 is: + index);
index = Arrays.binarySearch(b, 100);
System.out.println("The return value for keyword 100 is:" + index);
index = Arrays.binarySearch(b, 10);
System.out.println("The return value for keyword 10 is:+ index); }}Copy the code
The results are analyzed as follows:4 25 10 95 6 21After sorting, it is:4 6 10 21 25 95The keyword2The return value is: -1The keyword2It's not in the array, and2Is smaller than any element in the array, so its insertion point value should be element4The position of theta is theta1No keyword found from1Start) keyword20The return value is: -4The keyword20And it's not in the array, the first one in the array than20Large number is21, so20The insertion point value of is4Failed to find keywords from index from1Start) keyword30The return value is: -6The keyword30And it's not in the array, the first one in the array than30Large number is95, so30The insertion point value of is6Failed to find keywords from index from1Start) keyword100The return value is: -7The keyword100It's not in the array, and100Is larger than all the elements in the array, and the insertion point is length+1 为7No keyword index found from1Start) keyword10The return value of2The keyword10In an array, so returns its index in the array as2Find the keyword index from0Start)Copy the code
3. Fill () to fill the array
Populate the array with the specified value. You can specify the range of indexes to populate.
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest09 {
public static void main(String[] args) {
Integer[] a = new Integer[5];
Arrays.fill(a, 2);
System.out.println("Current array container:"+Arrays.toString(a));
Arrays.fill(a, 5);
// The number 3 covers and fills the entire Array container
System.out.println("Current array container:"+Arrays.toString(a));
// Start bit of padding
Integer startIndex = 1;
// Fill the end bit
Integer endIndex = 3;
Arrays.fill(a, startIndex, endIndex, 8);
System.out.println("Current array container:"+Arrays.toString(a)); }}/* Current array container: [2, 2, 2, 2, 2] Current array container: [5, 5, 5, 5] current array container: [5, 8, 8, 5, 5] */
Copy the code
4. Compare two arrays to equals
Returns true if two arrays of the specified type are equal to each other. Two arrays are considered equal if they contain the same number of elements and all corresponding pairs of elements in both arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. In addition, if both array references are NULL, they are considered equal.
Equals applies to one-dimensional arrays, while multidimensional arrays use deepEquals(), the same as equals.
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest10 {
public static void main(String[] args) {
int[] array1={5.6.9.3.2.4};
int[] array2={5.6.9.3.2.4};
int[] array3={6.5.9.3.2.4};
boolean flag1=Arrays.equals(array1,array2); // true
boolean flag2=Arrays.equals(array1,array3); // false
// What happens if you use equals directly?
boolean flag3 = array1.equals(array2); // Different heap memory addresses false array1==array2
System.out.println(flag1+""+flag2+""+flag3); }}Copy the code
5. Array toString toString() method
Returns a string representation of the contents of the specified array.
The string representation consists of a list of array elements enclosed in square brackets (“[]”).
Adjacent elements are separated by the character “, “(comma and space).
These elements are converted to strings by string.valueof (short). If a is null, “null” is returned.
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest11 {
public static void main(String[] args) {
String[] array01 = new String[3];
System.out.println(array01);
System.out.println(Arrays.toString(array01));
String[] array02 = {"The wu is empty"."Eight quit"."Tang's monk"}; System.out.println(array02); System.out.println(Arrays.toString(array02)); }}Copy the code
6. Clone array copyOf method
You can use this method if you want to increase the size of an array without changing its contents
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest13 {
public static void main(String[] args) {
int[] array1={5.6.9.3.2.4};
System.out.println("Array1 array length :"+array1.length);
int[] array2 = Arrays.copyOf(array1,array1.length+1);// Expand the capacity as required
System.out.println("Array2 array length :"+array2.length);
array2[0] =100;
System.out.println("array1:"+Arrays.toString(array1));
System.out.println("array2:"+Arrays.toString(array2)); }}Array1 :[5, 6, 9, 3, 2, 4] array2:[100, 6, 9, 3, 2, 4, 0] */
Copy the code
Array1 and array2 are two unrelated arrays
7. Clone array copyOfRange method
copyOfRange(int []original,int from,int to)
Copy the code
Original is the original int array, from is the start corner value and to is the end corner value. This includes from, but not to. Be in the state of [from,to]
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest14 {
public static void main(String[] args) {
int[] array1={5.6.9.3.2.4};
int[] array2 = Arrays.copyOfRange(array1,1.5);
System.out.println("Array2 array length :"+array2.length);
System.out.println("array2:"+Arrays.toString(array2)); }}// Array2's array length is 4
// array2:[6, 9, 3, 2]
Copy the code
This method is more efficient than looping through the copy array.
8. Array to list asList method
Returns a fixed-size list supported by the specified array. (Changes to the returned list are “written directly” to the array.) This method, along with collection.toarray (), acts as a bridge between array-based apis and collection-based apis. The returned list is serializable and implements RandomAccess.
package com.shxt.demo03;
import java.util.Arrays;
import java.util.List;
public class ArraysTest15 {
public static void main(String[] args) {
Integer[] array1={5.6.9.3.2.4};
List list = Arrays.asList(array1);
System.out.println("List length :"+list.size()); }}// List length :6
Copy the code
Avoid using primitive data type arrays to convert to lists
Modify the above code to be an array of primitive data types
package com.shxt.demo03;
import java.util.Arrays;
import java.util.List;
public class ArraysTest15 {
public static void main(String[] args) {
int[] array1={5.6.9.3.2.4};
List list = Arrays.asList(array1);
System.out.println("List length :"+list.size()); System.out.println(list); }}/** List length :1 [[I@4554617c] */
Copy the code
What happens when the program doesn’t get a 6 as expected, but an insane 1?
From this result we can fully prove that the elements in the list are ints.
You cannot add elements after converting to a list
package com.shxt.demo03;
import java.util.Arrays;
import java.util.List;
public class ArraysTest15 {
public static void main(String[] args) {
Integer[] array1={5.6.9.3.2.4};
List list = Arrays.asList(array1);
list.add(99);// Add elements}}Copy the code
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.shxt.demo03.ArraysTest15.main(ArraysTest15.java:10)
Copy the code
If you want to add data to the list, you need to reconstruct the list
package com.shxt.demo03;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraysTest15 {
public static void main(String[] args) {
Integer[] array1={5.6.9.3.2.4};
List list = Arrays.asList(array1);
// Convert again
List tempList = new ArrayList(list);
tempList.add(Awesome!);
// Can be addedSystem.out.println(tempList); }}Copy the code
9. Array hashCode hashCode
Returns a hash code based on the contents of the specified array. Arrays.hashcode (a) == arrays.hashcode (b) for any two identical Arrays A and B that satisfy arrays.equals (a, b).
The value returned by this method is the same as that obtained by calling the hashCode method on the List, which contains sequences representing instances of array A elements in the same order. If a is null, this method returns 0.
package com.shxt.demo03;
import java.util.Arrays;
public class ArraysTest12 {
public static void main(String[] args) {
int[] array1={5.6.9.3.2.4};
int[] array2={5.6.9.3.2.4};
int[] array3={6.5.9.3.2.4};
System.out.println(Arrays.hashCode(array1));
System.out.println(Arrays.hashCode(array2));
System.out.println(Arrays.hashCode(array3));
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
// All are differentSystem.out.println(array1.hashCode()); System.out.println(array2.hashCode()); System.out.println(array3.hashCode()); }}/*
1036461630
1036461630
1064167260
---------------------
1163157884
1956725890
356573597
*/
Copy the code