The Java.util.Arrays class makes it easy to manipulate an array, and all of the methods it provides are static. A static method belongs to a class, not to an object belonging to a class. So you can call directly using the class name plus the method name. arrays, as a tool class, can manipulate arrays well. Here are some of the main functions used.
1.fill method
The Fill method is mainly used to populate the array, here we give the simplest type of int (other types of the same)
See Arrays the Fill source
Example code:
Java code
-
Publicstaticvoidmain (string[] args) {
-
INTA[]=NEWINT[5];
-
Fill fills an array
-
Arrays.fill (a,1);
-
for (inti=0;i<5;i++)//output 5 x 1
-
System.out.println (A[i]);
-
}
Fill part of the array source code:
Example:
Java code
-
Publicstaticvoidmain (string[] args) {
-
INTA[]=NEWINT[5];
-
Fill fills an array
-
Arrays.fill (a,1,2,1);
-
for (inti=0;i<5;i++)//a[1]=1, the rest defaults to 0
-
System.out.println (A[i]);
-
}
2.sort method
From the method name, it is known that the array is sorted, still using the int type, other types.
Like a whole array sort, like
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]);
-
}
To specify the ordering of array parts:
Java code
-
Publicstaticvoidmain (string[] args) {
-
inta[]={2,4,1,3,7};
-
Arrays.sort (a,1,4); Output 2,1,3,4,7
-
for (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 see an array of type int. See Arrays Source
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
By using the BinarySearch method, the sorted array can be searched by binary method. See the source code as follows
Example:
Java code
-
Publicstaticvoidmain (string[] args) {
-
inta[]={2,4,1,3,7};
-
Arrays.sort (a);//Sort First
-
System.out.println (Arrays.binarysearch (A, 4));//binary lookup, Output 3
-
}
5.copyof method
Copying an array, arrays's copyof () method returns the array to the new array object, so you change the value of the element in the array, and it does not affect the original array
Such as:
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 ();
-
}
-
}
Java Arrays Tool class combat