首页 > 其他 > 详细

Compare the contents of two arrays

时间:2020-06-12 11:00:51      阅读:32      评论:0      收藏:0      [点我收藏+]

??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;
    }
}

Compare the contents of two arrays

原文:https://www.cnblogs.com/shmebluk/p/13097295.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!