Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a graph in java

Tags:

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.

like image 547
user1079226 Avatar asked Apr 16 '12 19:04

user1079226


People also ask

Does Java have a graph class?

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.

How do you add a vertex to a graph in Java?

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 .


2 Answers

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.

like image 123
angusiguess Avatar answered Oct 24 '22 07:10

angusiguess


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!

like image 22
Renaud Avatar answered Oct 24 '22 09:10

Renaud