I was writing an algorithm about graph theory in Java, and had the nodes on the graph defined as:
public class Node {
public String UUID;
public Set<Node> children;
// and some other fields & methods
@Override
public int hashCode() {
return UUID.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Node))return false;
Node other = (Node)obj;
return UUID.equals(other.UUID);
}
}
The UUID
field of any certain node on the graph was guaranteed to be unique (by input dataset), so I planned to store all the nodes in a HashSet<Node>
while reading the input dataset and building the adjacency list which was also defined as Set<Node> children
in Node class.
However, soon I noticed that I couldn't really get Node
instances stored in my HashSet<Node>
in an elegant way because Set
can't be randomly accessed.
The parentNode-childNode
The problem is: I want to get a specific Node
instance stored in the HashSet
with its specific UUID
(thus the same hashCode
) because I have to update the adjacency list of each node, WHILE I cannot really use any Set
to do this.
I guess I am confused. If I switch to Map<String, Node>
and make UUID
be the key, it just feels like dumb to define UUID
in Node class ( BUT UUID
should be a part of the Node logically!)
I've read this post and still believe that java should provide interface to access elements in Set (or at least some of its implementation) since this is not impossible through binary tree, just like C++ STL set.find() did.
Any suggestion on how I should hack this?