无法理解:如果任一指​​定数组将自身作为元素包含,则此方法的行为未定义

Unable to understand: If either of the specified arrays contain themselves as elements, the behavior of this method is undefined

我目前正在阅读关于数组 class 的 Java API 和 deepEquals(Object[] a1, Object[] a2) 方法,我遇到了以下短语:

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.

我似乎没有完全理解这句话的实际含义。

如果传递给此方法的数组包含自身,测试它是否等于另一个数组可能会导致无限递归(以 WhosebugError 结束),因为数组中总会有一个元素本身就是一个数组,这样你就多了一个级别来比较。

它可能不会在所有情况下都导致无限递归,因为如果例如两个比较数组的第一对元素不是数组,并且两个元素不相等,则该方法可以return false 没有检查数组的其余部分。

这可能是这种情况下没有定义行为的原因,因为可能无法 return 正确的输出(甚至 return 任何东西都不会发生异常)这样的输入被传递给方法。

例如:

Object[] objArr = new Object[1];
objArr[0] = objArr;

此数组包含自身,因此将其传递给 deepEquals 可能会导致无限递归。

表示如果数组名为a1且a1[i] = a1;其中 i < a1.length ,则方法行为未定义。这是因为如果该方法继续单独检查每个元素,那么在某些时候它可能会进入无限递归。

Object[] a1 = new Object[5];
a1[0] = a1; // array is an element of itself
Object[] a2 = new Object[5];
deepEquals(a1,a2); //behavior is undefined