Implementing equals and hashCode for objects with circular references in Java

I agree with the comment of I82Much that you should avoid having B referencing their parent: it’s information duplication, which usually only leads to trouble, but you might need to do so in your case.

Even if you leave the parent reference in B, as far as hash codes are concerned you should completely ignore the parent reference and only use the true inner variables of B to build the hash code.

The As are just containers and their value is fully determined by their content, which is the values of the contained Bs, and so should their hash keys.

If A is an unordered set, you must be very careful that the hash code you are building from the B values (or B hash codes) is not dependent on some ordering. For example, if the hash code is build by adding and multiplying the hash codes of the contained B‘s in some sequence, you should first order the hash codes by increasing order before computing the result of the sums/multiplications. Similarly, A.equals(o) must not depend on the ordering of the Bs (if unordered set).

Note that if you are using a java.util.Collection within A, then just fixing the Bs hash code by ignoring the parent reference will automatically give valid A hash codes since the Collections have good hash codes by default (ordering or not).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)