user1079226
user1079226

Reputation: 153

Creating a graph in java

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.

Upvotes: 15

Views: 51267

Answers (3)

Renaud
Renaud

Reputation: 2129

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!

Upvotes: 1

angusiguess
angusiguess

Reputation: 639

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.

Upvotes: 25

duffymo
duffymo

Reputation: 308733

You can write your own graph object or use something like Jung.

Upvotes: 0

Related Questions