How to write the hashCode() function for a cyclic graph node?

Viewed 1292

I have the following class that is used as part of a graph :

public class MyNode {

    private String name;

    private Set<MyNode> parents;

    private Set<MyNode> children;

    // getters and setters
}

When I use Eclipse's Source / Generate hashCode() and equals(), it generates this method:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((children == null) ? 0 : children.hashCode());
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + ((parents == null) ? 0 : parents.hashCode());
    return result;
}

The problem is that this method goes from the current object to its children, then while computing the hashCode() of the first child, it gets back to the original node through the parents.hashCode() but don't know that the hashCode() has already been computed there. It then reenters the children of the original node, and it gives a beautiful infinite loop.

Question : how can I check that two instances of MyNode are the same object while, at the same time, avoid the infinite loop? Is this acceptable to add a visited boolean in the MyNode class, for the purpose of stopping the exploration? Or is there a better solution?

Thanks!

3 Answers
Related