Can we find the hashcode
of a list
that contains itself as element
?
I know this is a bad practice, but this is what the interviewer asked.
When I ran the following code it throws a StackOverflowError
:
public class Main {
public static void main(String args[]) {
ArrayList<ArrayList> a = new ArrayList();
a.add(a);
a.hashCode();
}
}
Now here I have two questions:
StackOverflowError
?The hash code for conforming List
implementations has been specified in the interface:
Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:
int hashCode = 1; for (E e : list) hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
This ensures that
list1.equals(list2)
implies thatlist1.hashCode()==list2.hashCode()
for any two lists,list1
andlist2
, as required by the general contract ofObject.hashCode()
.
This doesn’t require that the implementation looks exactly like that (see How to compute the hash code for a stream in the same way as List.hashCode() for an alternative), but the correct hash code for a list only containing itself would be a number for which x == 31 + x
must be true
, in other words, it is impossible to calculate a conforming number.