比较Java中的整数数组。为什么不工作? [英] Comparing integer Arrays in Java. Why does not == work?

查看:72
本文介绍了比较Java中的整数数组。为什么不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,只是想出了关于语言的这个微妙的事实:如果我声明两个具有相同元素的整数数组,并使用 == 结果为 false 。为什么会发生这种情况?不应该比较评估为 true

I'm learning Java and just came up with this subtle fact about the language: if I declare two integer Arrays with the same elements and compare them using == the result is false. Why does this happen? Should not the comparison evaluate to true?

public class Why {

    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};

        System.out.println(a == b);
    }

}

>

推荐答案

使用 Arrays.equals(arr1,arr2 )方法。 == 运算符只是检查两个引用是否指向同一个对象。

use Arrays.equals(arr1, arr2) method. == operator just checks if two references point to the same object.

测试

       int[] a = {1, 2, 3};
       int[] b = a;    
       System.out.println(a == b); 
     //returns true as b and a refer to the same array  

       int[] a = {1, 2, 3};
       int[] b = {1, 2, 3};
       System.out.println(Arrays.equals(a, b));
       //returns true as a and b are meaningfully equal

这篇关于比较Java中的整数数组。为什么不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆