Java: How to test on array equality?

前端 未结 4 1424
清酒与你
清酒与你 2020-11-27 06:04

Why is the following code printing \"Different.\"?

boolean[][] a = { {false,true}, {true,false} };
bool         


        
4条回答
  •  情深已故
    2020-11-27 06:16

    It's really not obvious.

    First of all, the == operator just compare two pointers. Because a and b are distinct objects located at different memory addresses, a == b will return false (Hey, Java purists, I know that the == actually compare object identities. I'm just trying to be didactic).

    Now let's take a look at the equals() implementation of arrays:

    boolean[] c = new boolean[] { false, true, false };
    boolean[] d = new boolean[] { false, true, false };
    
    if (c.equals(d)) {
        System.out.println("Equals");
    } else {
        System.out.println("Not equals");
    }
    

    That would print Not equals because no array instance actually implements the equals() method. So, when we call .equals() we are actually calling the Object.equals() method, which just compare two pointers.

    That said, notice that your code is actually doing this:

    boolean[] a0 = new boolean[] { false, true };
    boolean[] a1 = new boolean[] { true, false };
    boolean[] b0 = new boolean[] { false, true };
    boolean[] b1 = new boolean[] { true, false };
    boolean[][] a = new boolean[][] { a0, a1 };
    boolean[][] b = new boolean[][] { b0, b1 };
    
    if (Arrays.equals(a, b) || a == b)
        System.out.println("Equal.");
    else
        System.out.println("Different.");
    

    The Arrays.equals(a, b) will eventually call a0.equals(b0) which will return false. For this reason, Arrays.equals(a, b) will return false as well.

    So your code will print Different. and we conclude that Java equality can be tricky sometimes.

提交回复
热议问题