I'm trying to write DagNode class in Java whereby two nodes are logically equal iff they are equal as references.
The idea in C++ —(I'm from C++)— would be to use smart pointers and reference counting:
When a node is created, I'll look up in some table if that node already exists. If so, I'll return a pointer to the old one. Otherwise, make anew node.
Overloaded C++ methods like copy constructors and destructors will do ref-counting, and when the ref-count of a node drops to 0, the node is evicted from the above-mentioned table. (C++ will also free the memory.)
However, there seems to be no way to automatically do ref-counting in Java. I'll need to do ref-counting to know when to evict a node from the table (so that it can be garbage collected), and I really want to avoid calling node->incRef()
and node->decRef()
at the start and end of each function.
How do we do this C++ idiom in Java?