比较Java中的整数数组.为什么不= =工作?

rod*_*ves 6 java comparison compare

我正在学习Java,并且想出了关于语言的这个微妙的事实:如果我声明两个具有相同元素的整数数组并使用==结果比较它们false.为什么会这样?不应该比较评估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);
    }

}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Per*_*ror 32

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

测试:

       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
Run Code Online (Sandbox Code Playgroud)