Java 11 Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The  Arrays.equals(Object a, Object b) and  Arrays.deepEquals(Object a, Object b) methods behave the same way as the Objects.equals(Object a, Object b) and Objects.deepEquals(Object a, Object b) methods:

Integer[] ints1 = {1,2,3};
Integer[] ints2 = {1,2,3};
System.out.println(Arrays.equals(ints1, ints2));
//prints: true
System.out.println(Arrays.deepEquals(ints1, ints2));
//prints: true
System.out.println(Arrays.equals(iints1, iints2));
//prints: false
System.out.println(Arrays.deepEquals(iints1, iints2));
//prints: true

In fact, the Arrays.equals(Object a, Object b) and  Arrays.deepEquals(Object a, Object b) methods are used in the implementation of the Objects.equals(Object a, Object b) and Objects.deepEquals(Object a, Object b) methods.

To summarize, if you would like to compare two objects, a and b, by the values of their fields, then:

  • If they are not arrays and a is not null, use a.equals(Object b)
  • If they are not arrays and each or both objects can be null, use Objects.equals(Object a, Object b)
  • If both can be arrays and each or both can be null, use Objects.deepEquals(Object a, Object b)

The Objects.deepEquals(Object a, Object b) method seems to be the safest one, but it does not mean that you must always use it. Most of the time, you will know whether the compared objects can be null or can be arrays, so you can safely use other methods, too.