判断两个数组是否相等

首先定义两个数组
int[] arry1={1,2,3,4,5,6};
int[] arry2={1,2,3,4,5,6};

两个数组相等的依据是,官方注释说到:In other words, two arrays are equal if they contain
the same elements in the same order. Also,two array references are
considered equal if both are null. 谷歌翻译:换句话说,如果两个数组包含相同顺序的相同元素,则它们相等。
另外,如果两个数组引用均为 null ,则认为它们相等

public class Main {
    public static void main(String[] args) {
        System.out.println(matchArry());
    }

    private static boolean matchArry() {
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {1, 2, 3, 4, 5};
        if (arr1.length == arr2.length) {
            for (int i = 0; i < arr1.length; i++) {
                if (arr1[i] != arr2[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}



而对于无序数组来说,当只需要比较两个数组的内容是否相同而不需要考虑顺序时,只需先把数组顺排即可

public class main {
    public static void main(String[] args) {
        int[] artg={3,1,6,2,5,4};
        int[] aty={1,2,4,3,6,5};
        Arrays.sort(artg);     //对两数组进行排序
        Arrays.sort(aty);
        if (Arrays.equals(artg,aty)){
            System.out.println("true");
        }else{
            System.out.println("false");
        }
    }
}

在这里插入图片描述
代码量减少了一半,而且对无序数组也适用!

  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值