I want to create a program that creates a graph (to be specific a program graph), which stores values at nodes and also stores what other nodes each individual nodes are connected to.
I am thinking of doing this using linked list. Is this the right way to go about it? Any other advice would be greatly appreciated.
The Graph class is implemented using HashMap in Java. As we know HashMap contains a key and a value, we represent nodes as keys and their adjacency list in values in the graph. Illustration: An undirected and unweighted graph with 5 vertices.
Adding a VertexThe Java implementation of a Graph has an . addVertex() instance method that takes in data and creates a new Vertex , which it then adds to vertices . The method returns the new Vertex .
For the most part it's a good idea to model your graph with an adjacency list. There are probably existing frameworks to do this, but if you're interested in the representation as an exercise, you generally want two things. First, a HashMap containing all of your nodes, the node label for your node can be the key, the node itself is the value.
The Java API documents HashMaps here.
In each node object, you'll want a list of nodes that are adjacent to that node. This is best done with an ArrayList, which is documented here.
Here's how it might be organized.
import java.util.Hashmap;
import java.util.ArrayList;
class Node {
String label;
ArrayList<Node> adjacencyList;
}
HashMap<String, Node> graph = new HashMap<String, Node>();
Most algorithms you'd want to run on a graph will run well on this representation.
What you are looking for seems to be a TreeNode API. Actually there is a nice one inside the swing package which is already present in Java SE the default implementation being: javax.swing.tree.DefaultMutableTreeNode. It can be used outside of a Swing application and provide a very standard TreeNode model.
You will find every thing to fit your need: getChildren(), getParent(), setUserObject()... etc and every recursive method for crawling and searching over the nodes tree.
The good news is you will earn the ability to write a JTree UI in a few minutes!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With