educative.io

HashSet contains check by value or reference?

In the case of detecting loops in LinkedList we have inserted LL nodes in a HashSet and then we check using a contains() method for loops. When looking through HashSet documentation, it seems like the comparison is by value rather than by reference. However, when I implement inserting two nodes with same data (but different references), I do not get a “loop” detection. However, if I point one of the Nodes in the LL to the Head node and run the DetectLoop(), I do get “Loop detected”. Could someone share more details? Ideally, it would be great to have this reference versus value comparison added to this section of the course itself, along with details of how exactly this comparison is taking place (since “data” is a field inside Node, and Node is what we are adding and comparing, and we have not overriden the equals() method for Node)

Dear Abhishek,

Thank you for reaching out, we are happy to hear from you.

In HashSets, If we have 2 or more nodes having the same ‘value’, the first node containing the value is returned while searching. Because we are looking for the right key, irrespective of where it is stored. But in detecting the loop, the only node pointing to any other node (in the form of a loop) will be detected. Since, when a node points to another its ‘reference’ is stored.

Hope you got it.
If you have any further queries please let us know, we’ll be pleased to help.