Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find hash code of a Collection?

Tags:

java

To my understanding, the following code should print HashCode of collection, as i am printing its HashCode directly.

However, when I run the following code i am getting Stack overflow error:

    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 some one explain this behavior ?

like image 394
Sachin Sachdeva Avatar asked Dec 23 '22 16:12

Sachin Sachdeva


2 Answers

You have created a Collection that contains itself as an element.

A LinkedHashSet's hashCode() is a function of its elements' hashCodes (as you can see below), so computing the 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;
}
like image 194
Eran Avatar answered Dec 26 '22 05:12

Eran


It's caused by this line:

cl.add(cl);

You're adding the collection to itself. Since the hash code of the set is based on the elements contained in the set, the hashCode() method of cl will be called recursively.

From the AbstractSet.hashCode() javadoc (emphasis mine):

Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash code of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of Object.hashCode().

like image 43
Robby Cornelissen Avatar answered Dec 26 '22 05:12

Robby Cornelissen