Ravindra's answer gives a good explanation for point 1. To comment on question 2:
Is it possible to find hash code in this way?
Something is circular here. At least one of these 2 must be wrong in the context of this stack overflow error:
- that the hash code of the list must take those of its elements into account
- that it's OK for a list to be its own element
Now, because we're dealing with an ArrayList
, the first point is fixed. In other words, maybe you need a different implementation to be able to meaningfully compute a hash code of a recursive list... One could extend ArrayList
and skip adding the hash codes of elements, something like
for (E e : this)
if(e == this) continue; //contrived rules
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
Using such a class instead of ArrayList
, you could.
With ArrayList
, the second point is wrong. So if the interviewer meant "Is it possible to find hash code in this way (with an array list)?", then the answer is no, because that's absurd.