1

I'm currently reading Java API on Arrays class and for deepEquals(Object[] a1, Object[] a2) method, I have encountered the following phrase:

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.

I don't seem to completely understand what the phrase actually means.

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 2
    It's a fairly straightforward phrase; which part don't you understand? If you understand the concept of an array containing itself, and you understand what is meant by undefined behavior, then I don't see what you're having trouble with. If you don't understand either of those things, then say so. – davmac Apr 03 '16 at 10:11

2 Answers2

4

If an array passed to this method contains itself, testing if it is equal to the other array may cause infinite recursion (ending in StackOverflowError), since there will always be an element of the array which is itself an array, so you'll have one more level to compare.

It may not cause an infinite recursion in all scenarios, since if, for example, the first pair of elements of the two compared arrays is not an array, and the two elements are not equal, the method can return false without ever examining the rest of the arrays.

That's probably the reason there is no defined behavior for this case, since it may not be possible to return a correct output (or even return anything at all without an exception occurring) when such an input is passed to the method.

For example :

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

This array contains itself, so passing it to deepEquals may cause infinite recursion.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • thank you very much for your help!! wording in documentation can be hard to understand for beginners like me. – Thor Apr 03 '16 at 12:07
1

It states that if the name of array is a1 and a1[i] = a1; where i < a1.length , then the method behavior is undefined. It is because if the method keeps checking each element individually , then at some point it could go into infinite recursion.

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
lobo
  • 164
  • 1
  • 6
  • You missed "either directly or indirectly through one **or more** levels of arrays". Your example only shows one level. – davmac Apr 04 '16 at 10:29