How do I add nodes & edges to graph?
MutableValueGraph<GraphNode, Double> weightedGraph = ValueGraphBuilder.directed().build();
GraphNode a = new GraphNode("Jonathan", 20);
GraphNode b = new GraphNode("Nicolas", 40);
GraphNode c = new GraphNode("Georgia", 30);
weightedGraph.putEdgeValue(a, b, 2.0);
weightedGraph.putEdgeValue(a, c, 4.5);
This will produce a graph like the following (arrows going down):
(Jonathan, 20)
/ \
2.0 4.5
/ \
(Nicolas, 40) (Georgia, 30)
Do I have to override the equals & hashCode methods in the custom node class?
It's not strictly necessary, but it's highly encouraged, because otherwise, with the following code example, the graph will likely look different to what you'd expect it to be.
MutableValueGraph<GraphNode, Double> weightedGraph = ValueGraphBuilder.directed().build();
GraphNode a = new GraphNode("Jonathan", 20);
GraphNode b = new GraphNode("Nicolas", 40);
GraphNode c = new GraphNode("Georgia", 30);
weightedGraph.putEdgeValue(a, b, 2.0);
weightedGraph.putEdgeValue(a, c, 4.5);
weightedGraph.putEdgeValue(b, new GraphNode("Luke", 10), 6.0);
weightedGraph.putEdgeValue(c, new GraphNode("Luke", 10), 1.5);
With custom equals()
and hashCode()
implementations in GraphNode
, the graph will produce the following expected shape:
(Jonathan, 20)
/ \
2.0 4.5
/ \
(Nicolas, 40) (Georgia, 30)
\ /
6.0 1.5
\ /
(Luke, 10)
But without equals()
and hashCode()
, the value graph will be unable to tell that the two new GraphNode("Luke", 10)
s are logically the same node, and so it will produce the following erroneous shape:
(Jonathan, 20)
/ \
2.0 4.5
/ \
(Nicolas, 40) (Georgia, 30)
| |
6.0 1.5
| |
(Luke, 10) (Luke, 10)