On Java 7's equals() and deepEquals()

前端 未结 4 1200
我在风中等你
我在风中等你 2021-02-19 03:39

Method description says:

Returns true if the arguments are deeply equal to each other and false otherwise... Equality is determined by using the equ

4条回答
  •  长发绾君心
    2021-02-19 03:49

    String[] firstArray  = {"a", "b", "c"};
    String[] secondArray = {"a", "b", "c"};
    
    System.out.println("Are they equal 1    ? " + firstArray.equals(secondArray) );
    System.out.println("Are they equal 2    ? " + Objects.equals(firstArray, secondArray) );
    
    System.out.println("Are they deepEqual 1? " + Arrays.deepEquals(firstArray, secondArray) );
    System.out.println("Are they deepEqual 2? " + Objects.deepEquals(firstArray, secondArray) );
    

    will return

    Are they equal 1    ? false
    Are they equal 2    ? false
    Are they deepEqual 1? true
    Are they deepEqual 2? true
    

    How come the "shallow" equals methods return false? This is because in Java, for arrays, equality is determined by object identity. In this example, firstArray and secondArray are distinct objects.

    Doing String[] secondArray = firstArray instead will therefore return true for all four tests.

提交回复
热议问题