Determining whether the two identical arrays 16

Analyzing two arrays are the same

Case needs

Definition of a method for comparing the contents of the two arrays are the same and different.
int [] of arr1 = {10, 30, 50, 70, 90};
int [] = {arr2 is 10, 30, 50, 70, 90};

analysis

a, defines two arrays.
B, defines a method of determining contents of the array package is the same function, so this method should accept two arrays. This method is best to give it a return value, think the same returns true, and vice versa returns false.
C call the method passed in the array, compare the results obtained:. False | true.
Note: In the use of the package as long as the time to perform this method will return immediately terminated, the following procedure is not executed.
Used for determining whether the same type Boolean

public class ExecDemo {
    public static void main(String[] args) {
        // 1.定义2个数组。
        int[] arr1 = {10 , 30 , 50 , 70 , 90};
        int[] arr2 = {10 , 30 , 50 , 70 , 90};
        // 3.传入两个数组到方法中进行比较得到方法的返回值
        boolean result = compare(arr1 , arr2);
        System.out.println(result);
    }

    // 2.定义一个方法封装判断数组内容是否相同的功能
    public static boolean compare(int[] arr1 , int[] arr2){
         // 4.判断2个数组的内容是否相同
         // 判断2个数组的长度是否相同,如果长度不相同直接返回false.
        if(arr1.length != arr2.length)  return false;

        // 5.到这儿数组的长度已经是相同的,接下来要判断具体的每个元素值是否也相同!
        // 使用一个循环遍历两个数组的元素进行比较
        for(int i = 0 ; i < arr1.length ; i++ ) {
            // 6.判断元素内容是否相同 ,如果发现有一个不同就直接返回false
            if(arr1[i] != arr2[i] ) return false;
        }

        // 7.代码如果执行到这儿了,说明两个数组的每个元素都相同了,直接返回true
        return true;
    }
}
Published 34 original articles · won praise 16 · views 289

Guess you like

Origin blog.csdn.net/qq_41005604/article/details/105181846