How to compare two object arrays in Java?

后端 未结 6 918
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 19:46

I have two object arrays like so:

Object[] array1 = {0, 1, 2, 3};
Object[] array2 = {0, 1, 2, 3};

I would like to know if the arrays are eq

6条回答
  •  爱一瞬间的悲伤
    2020-12-09 20:16

    Use Arrays.deepEquals(). This does the same job as Arrays.equals() but also works with nested arrays.

    Returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object[],Object[]) method, this method is appropriate for use with nested arrays of arbitrary depth.

    Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.

    Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:

    • e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
    • e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
    • e1 == e2
    • e1.equals(e2) would return true.

    Note that this definition permits null elements at any depth.

    If either of the specified arrays contain themselves as elements either directly or indirectly through one or more levels of arrays, the behavior of this method is undefined.

提交回复
热议问题