Archive for October, 2011

Simple graph implementation in java

Posted on October 13th, 2011 by admin  |  No Comments »

Below is the illustration and class code for Graph structure implementation using java language.A mathematically Graph is  connection of nodes in a directional or non-directional way below graph has child parent relationship. node naming convention like 101 , 201 is important for understanding of this demo as

0 => initial node

101 , 102, 103 => level 1st node

201, 202 etc => level 2 node

mathematical graph structure using java

Class Node


public class Node {

private int id;
public Node(int id){
this.id  = id;
}
public int getId(){
return id;
}
}

Class Graph

</strong>

import java.util.HashSet;

public class Graph {

private HashSet&lt;Graph&gt; childs = new HashSet&lt;Graph&gt;();
private Node rootNode;

// initialization of graph
public Graph(Node node) {
this.rootNode = node;
}

// get connected graphs/nodes for iteration
public HashSet&lt;Graph&gt; getChildSet() {
return childs;
}

// Adding graph to graph
public void addChild(Graph g) {
childs.add(g);
}

// Adding Node to graph
public void addChild(Node node){
Graph g = new Graph(node);
childs.add(g);
}

public Node getRootNode(){
return rootNode;
}

// returns number sof childs for a graph
public int count() {
return childs.size();
}
public String toString(){
String temp = rootNode.getId()+" =&gt; {";
for(Graph child : childs){
temp += child.toString()+", ";
}
temp += "}";
return temp;
}
}

Now run this from test.java class

</span></strong>

public class test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

// Creating  subgraph
Graph g1 = new Graph(new Node(101));
g1.addChild(new Node(201));
g1.addChild(new Node(202));
g1.addChild(new Node(203));

// Creating and populating main graph and then adding subgraph to it
Graph g0 = new Graph(new Node(0));
g0.addChild(new Node(101));
g0.addChild(new Node(102));
g0.addChild(g1);

System.out.println(g0);

}

}

Outout of the program

0 => {101 => {203 => {}, 201 => {}, 202 => {}, }, 102 => {}, 101 => {}, }