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 ?
You have created a Collection
that contains itself as an element.
A LinkedHashSet
's hashCode()
is a function of its elements' hashCode
s (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;
}
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 thats1.hashCode()==s2.hashCode()
for any two setss1
ands2
, as required by the general contract ofObject.hashCode()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With