Basic methods of manipulating arrays (java.util.Arrays)

Basic methods of manipulating arrays

Topic description:
Perform some common basic operations on the array:
 1. Determine whether the two arrays are equal
 2. Output the array information
 3. Fill the specified value into the array
 4. Sort the array
 5. Find the elements in the array

Problem-solving ideas:
java.util.Arrays: A tool class for manipulating arrays, which defines many methods for manipulating arrays:

1.boolean equals(int[] a,int[] b): determine whether two arrays are equal
2.String toString(int[] a): output array information
 System.out.println(arry): output the array address
3.void fill(int[] a,int val): fill the specified value into the array.
4.void sort(int[] a): sort the array.
5.int binarySearch(int[] a,int key): Find elements in the array

Supplementary note: the previous boolean, String, void, etc. are the return value types

The Java code for this question:

import java.util.Arrays; //导包
public class ArrayTest {
    
    
	public static void main(String[] args) {
    
    
		
		//1.boolean equals(int[] a,int[] b):判断两个数组是否相等。
		int[] arr1 = new int[]{
    
    1,2,3,4,5};
		int[] arr2 = new int[]{
    
    1,3,2,4,5};
		boolean isEquals = Arrays.equals(arr1, arr2);
		System.out.println(isEquals);
		
		//2.String toString(int[] a):输出数组信息。
		System.out.println(Arrays.toString(arr1));
		
		//3.void fill(int[] a,int val):将指定值填充到数组之中。
		Arrays.fill(arr1, 10);
		System.out.println(Arrays.toString(arr1));
		
		//4.void sort(int[] a):对数组进行排序。
		Arrays.sort(arr2);
		System.out.println(Arrays.toString(arr2));
		
		//5.int binarySearch(int[] a,int key):查找数组中的元素
		int[] arr3 = new int[]{
    
    -98,-34,2,34,54,66,79,105,210,333};
		int index = Arrays.binarySearch(arr3, 210);
		System.out.println(index);//如果index是负数,则未找到
		if(index >= 0){
    
    
			System.out.println(index);
		}else{
    
    
			System.out.println("未找到!");
		}		
	}
}

Guess you like

Origin blog.csdn.net/qq_45555403/article/details/114173805