Hash code of ArrayList that contains itself as element

Joker :

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:

  1. Why is there a StackOverflowError?
  2. Is it possible to find the hash code in this way?
Holger :

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 that list1.hashCode()==list2.hashCode() for any two lists, list1 and list2, as required by the general contract of Object.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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=414493&siteId=1