Compare the contents of two arrays

✍️Define a methed to compare the contents of two arrays and return the result .

定义一个方法,用于比较两个数组的内容是否相同.
👉思路:

  1. 定义两个数组,分别使用静态初始化完成数组元素的初始化
  2. 定义一个方法,用于比较两个数组的内容是否相同
  3. 比较两个数组的内容是否相同,按照下面的步骤实现就可以了
    1.首先比较数组长度,如果长度不相同,数组内容肯定不相同,返回false
    2.其次遍历,比较两个数组中的每一个元素,只要有元素不相同,返回false
    3.最后循环遍历结束后,返回true
    调用方法
    输出结果
    代码如下:
public class test01 {
    public static void main(String[] args) {
        //定义两个数组,分别使用静态初始化完成数组元素的初始化
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {1, 2, 3, 4, 6};
        System.out.println();
        test01 t = new test01();
        //调用方法,输出结果
        System.out.println(t.compare(a, b));
    }
    //定义一个方法,用于比较两个数组的内容是否相同
    /*
        两个明确:
            返回值类型:boolean
            参数:int[] arr, int[] arr2
     */
    public boolean compare(int[] a, int[] b) {
        //首先比较数组长度,如果长度不相同,数组内容肯定不相同,返回false
        if (a.length == b.length) {
            //其次遍历,比较两个数组中的每一个元素,只要有元素不相同,返回false
            for (int i = 0; i < a.length; i++) {
                if (a[i] != b[i]) {
                    return false;
                }
            }
            // 遍历完成返回ture
            return true;
        }
        return false;
    }
}
posted @ 2020-06-12 08:10  juyss  阅读(140)  评论(0)    收藏  举报