The java.util.Arrays class can easily manipulate arrays, and all methods it provides are static. Static methods belong to the class, not the object belonging to the class. Therefore, you can directly use the class name plus the method name to call. As a tool class, Arrays can operate arrays very well. The following are several functions that are mainly used.
1.fill method
The fill method is mainly used to fill arrays. Here we list the simplest int type (the same as other types)
See Arrays' fill source code
Sample code:
Java code
publicstaticvoidmain(String[] args) {inta[]=newint[5];//fill fills the array Arrays.fill(a,1); for(inti=0;i<5;i++)//Output 5 1System.out.println(a[i]);}Fill in part of the array source code:
Example:
Java code
publicstaticvoidmain(String[] args) {inta[]=newint[5];//fill fills the array Arrays.fill(a,1,2,1);for(inti=0;i<5;i++)//a[1]=1, the rest defaults to 0System.out.println(a[i]);}2.sort method
From the method name, we all know that it is to sort the array, but still use the int type, other types are the same.
There is also the entire array sort, such as
Java code
publicstaticvoidmain(String[] args) {inta[]={2,4,1,3,7};Arrays.sort(a);for(inti=0;i<5;i++)//Ascending System.out.println(a[i]);}Specify the array partial sort:
Java code
publicstaticvoidmain(String[] args) {inta[]={2,4,1,3,7};Arrays.sort(a,1,4); //Output 2,1,3,4,7for(inti=0;i<5;i++)System.out.println(a[i]);}3.equals method
Used to compare whether the element values in two arrays are equal, or to look at an array of type int. See Arrays source code
Example:
Java code
publicstaticvoidmain(String[] args) {inta[]={2,4,1,3,7};inta1[]={2,4,1,5,7};System.out.println(Arrays.equals(a1, a)); //Output false}4.binarySearch method
The binarySearch method can perform binary search operations on sorted arrays. See the source code as follows
Example:
Java code
publicstaticvoidmain(String[] args) {inta[]={2,4,1,3,7};Arrays.sort(a);//Sort System.out.println(Arrays.binarySearch(a, 4));//Binary search, output 3}5.copyof method
Copy the array, the array returned by Arrays' copyOf() method is a new array object, so you change the element value in the array and will not affect the original array.
like:
Java code
importjava.util.Arrays;publicclassArrayDemo {publicstaticvoidmain(String[] args) {int[] arr1 = {1, 2, 3, 4, 5};int[] arr2 = Arrays.copyOf(arr1, arr1.length);for(inti = 0; i < arr2.length; i++)System.out.print(arr2[i] + " ");System.out.println();}}The above is the actual Java Arrays tool practice introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!