How to find the hash code of a collection?

As far as I understand, the following code should print HashCodecollections, since I print it HashCodedirectly.

However, when I run the following code, I get an error Stack overflow:

    public class Test1  {

    public static void main(final String[] args) {
        m1(new LinkedHashSet<Collection<?>>());
    }

    private static void m1(final Collection<Collection<?>> cl) {
        cl.add(cl);
        try {
            System.out.println(cl.hashCode());
        } catch (Error err) {
            System.out.println(err);
        }
    }

}

Can someone explain this behavior?

+4
source share
2 answers

You created Collectionone that contains itself as an element.

A LinkedHashSet hashCode()is a function of its elements hashCode(as you can see below), so the calculation hashCode()leads to infinite recursion.

public int hashCode() {
    int h = 0;
    Iterator<E> i = iterator();
    while (i.hasNext()) {
        E obj = i.next();
        if (obj != null)
            h += obj.hashCode(); // when obj == this, as in your case, this
                                 // call leads to infinite recursion
    }
    return h;
}
+6
source

This is caused by this line:

cl.add(cl);

. - , , hashCode() cl .

AbstractSet.hashCode() javadoc ( ):

- . - - , - . , s1.equals(s2) , s1.hashCode()==s2.hashCode() s1 s2, Object.hashCode().

+4

Source: https://habr.com/ru/post/1680853/


All Articles