I have a class defining a node (a point with three double coordinates).
public class Node {
private final double x, y, z;
public Node() {
}
public Node(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public void setCoordinates(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
I need to create a lot of nodes and give them integer IDs, but I must avoid duplicates.
The method to create a node looks like this:
private Node vertex = new Node(0, 0, 0);
private final AtomicInteger nodeCounter = new AtomicInteger();
private final Map<Node, Integer> nodeList = new HashMap<>();
public int addNode(final double x, final double y, final double z) {
vertex.setCoordinates(x, y, z);
int nodeId;
if(nodeList.get(vertex) == null) {
nodeId = nodeCounter.incrementAndGet();
nodeList.put(new Node(x, y, z), nodeId);
} else {
nodeId = nodeList.get(vertex);
}
return nodeId;
}
Of course, this does not work because the get
function of the HashMap
always returns null
.
So I guess I need to override the hashCode
method in the Node
class.
I have seen here how to do it for a single double, but I don't know how to create a hash function that would take into account the three coordinates of the node.
Do I also have to override the equals
function? Or is the hashCode function enough?