2020-04-14
- Arrays provides a copyOfRange method for array replication. The difference is that System.arraycopy needs to prepare the target array in advance and allocate the length. copyOfRange only needs the source array. By returning a value, you can get the target array.
package Arrays contact; import java.lang.reflect.Array; import java.util.Arrays; public class copytext { public static void main(String[] args) { int a[]=new int[]{1,2,3,4,5}; // copyOfRange(int[] original, int from, int to) // The first parameter represents the source array // The second parameter indicates the start position (obtained) // The third parameter indicates the end position (not available) int[] b= Arrays.copyOfRange(a,0,5); for (int i=0;i<b.length;i++) { System.out.println(b[i]); } } }
This method needs to pass three parameters: copy array, start node sequence number and end node sequence number. (the array has started 0, so the end sequence number content will not be copied.)
2. Convert to string
package Arrays contact; import java.lang.reflect.Array; import java.util.Arrays; public class copytext { public static void main(String[] args) { int a[] = new int[]{1, 2, 3, 4, 5}; String as=Arrays.toString(a); System.out.println(as); } }
Array.tostring method, which converts an array into a string. The converted content includes [].
3. sort() a sort method in arryas
package Arrays contact; import java.lang.reflect.Array; import java.util.Arrays; public class copytext { public static void main(String[] args) { int a[] = new int[]{78,24,105,33,99}; Arrays.sort(a);//Method call String as=Arrays.toString(a); System.out.println(as); } }
The sort() method sorts the contents of the array from small to large;
3.1 location of query elements
It should be noted that sort must be used for sorting before searching with binarySearch
If there are more than one identical element in the array, the search result is uncertain
package Arrays contact; import java.lang.reflect.Array; import java.util.Arrays; public class copytext { public static void main(String[] args) { int a[] = new int[]{78,24,105,33,99}; Arrays.sort(a);//Method call String as=Arrays.toString(a); System.out.println(as); System.out.println("99 The ordinal in the array is"+Arrays.binarySearch(a,99)); } }
Results:
[24, 33, 78, 99, 105]
99 the sequence number in the array is 3
Process finished with exit code 0
Note: Arrays.binarySearch() gets the angle sign of search value [small 1])
4. Judge whether it is equal
Compare the contents of two arrays
package Arrays contact; import java.lang.reflect.Array; import java.util.Arrays; public class copytext { public static void main(String[] args) { char a[]=new char[]{'a','s','d','w'}; char b[]=new char[]{'a','s','d','w'}; System.out.println(Arrays.equals(a,b)); } }
The return value of the method is true or false, so it cannot be located in different locations precisely. Please note that