A data structure that comprises edges and vertices is referred to as a graph. The vertices are nodes/labels that hold values, and edges connect these vertices with each other. The term “generic graph” typically refers to a graph that can be created once and reused by entering different data. In Java, users can create a generic graph using a generic class.
This article will discuss in detail the implementation of the generic graph in Java using a Hashmap.
How to Implement/Execute a Generic Graph in Java?
A generic graph can be implemented using the generic class with the assistance of HashMap. A HashMap is basically employed because it consists of key-value pairs. In this context, the nodes are indicated by keys and the adjacency list serves as the values in the graph. This makes the implementation of a generic graph easy.
Example: Implementation of Generic Graph in Java
The following code states the implementation of the generic graph in Java using different functions.
//Import the java.util package.
import java.util.*;
//Declare a class for a graph.
class Graph<G> {
//To store the edges hashmap has been used.
private Map<G, List<G> > map = new HashMap<>();
//To add a new vertex
public void insertvertex(G s)
{
//The put() method to insert the vertex
map.put(s, new LinkedList<G>());
}
//To add an edge between the destination and the source.
public void insertedge(G src,G dest,boolean bidirect)
{
//Add vertex to the source
if (!map.containsKey(src))
insertvertex(src);
//Add vertex to the destination
if (!map.containsKey(dest))
insertvertex(dest);
map.get(src).add(dest);
if (bidirect == true) {
map.get(dest).add(src);
}
}
//To count the vertex in the graph
public void countvertex()
{
System.out.println("This graph contains "+ map.keySet().size()+ " vertex");
}
//The edges present in a graph.
public void countedges(boolean bidirect)
{
int count = 0;
for (G v : map.keySet()) {
count += map.get(v).size();
}
if (bidirect == true) {
count = count / 2;
}
//statement to print the edges in the graph.
System.out.println("This graph contains "+ count + " edges.");
}
//The current graph has the entered vertex or not.
public void hasvertex(G s)
{
//If the key value matches the graph containing the vertex.
if (map.containsKey(s)) {
System.out.println("The graph has a vertex that is" +s);
}
//If the desired vertex is not present in the graph else {
System.out.println("The graph has no vertex as " + s);
}
}
//To check the edge.
public void hasedge(G s, G d)
{
//If the system contains an edge.
if (map.get(s).contains(d)) {
System.out.println("The graph has an edge between "+ s + " and " + d + ".");
}
else {
//The system does not contain an edge.
System.out.println("There is no edge between "+ s + " and " + d + ".");
}
}
@Override//The public constructor
public String toString()
{//An object created as builder
StringBuilder builder = new StringBuilder();
for (G v : map.keySet()) {
builder.append(v.toString() + ": ");
for (G w : map.get(v)) {
builder.append(w.toString() + " ");
}
builder.append("\n");
}
return (builder.toString());
}
}
// Driver Code
public class Main {
public static void main(String args[])
{
Graph<String> f = new Graph<String>();
//Adding the edges and keeping the bidirectional value “true”.
f.insertedge("a", "b", true);
f.insertedge("a", "e", true);
f.insertedge("b", "c", true);
f.insertedge("b", "d", true);
f.insertedge("b", "e", true);
f.insertedge("c", "d", true);
f.insertedge("d", "e", true);
//printing the graph
System.out.println("THE GRAPH IS :\n"+ f.toString());
//the graph has the defined edge or not
f.hasedge("c", "d");
//The graph contains "f" as a vertex or not.
f.hasvertex("f");
//The total number of vertices present.
f.countvertex();
f.countedges(true);
}
}
In the above code:
- First, a HashMap is declared.
- After that, a function for adding new vertices using the put() method is declared.
- A function named “insertedge()” is created to add the edges between the graph’s source and destination.
- Vertices are added to the source and destination respectively.
- Two functions, “countvertex()” and “countedges()”, are declared to count the vertices and edges present in the graph.
- A new function named “hasedge()” is created. Within the function, the “if statement” verifies whether the edges and the vertices are present in the graph.
- The override method declares the adjacency list for each vertex.
- The object for the “Graph class” is created in the next step.
- Edges are added, and the bidirectional value is set to “true”.
- Hardcoded statements are passed to check whether the code responds correctly.
Output
The output shows that a graph has been created, and the adjacency list for each vertex has been printed:
This sums up the method to implement a generic graph in Java using HashMap.
Conclusion
A generic graph can be implemented using the generic class with the assistance of HashMap.Generic graphs can be parameterized with different data types, such as int, string, custom objects, etc., allowing us to change the data that the graph holds while using the same graph structure. In this write-up, we have demonstrated the implementation of the generic graph in Java using the generic class.