# What Is Graph in Data Structure Java?

//

Heather Bennett

In the field of data structures, a graph is a non-linear data structure that consists of a set of vertices (also known as nodes) and a set of edges. A graph can be used to represent various real-life scenarios such as social networks, computer networks, transportation networks, and more. In this article, we will explore the concept of graphs in the context of Java programming language.

## Graph Representation

A graph can be represented using two popular approaches: adjacency matrix and adjacency list. Let’s discuss each approach in detail:

An adjacency matrix is a 2D array where each element represents an edge between two vertices. If there is an edge between vertex i and vertex j, then matrix[i][j] will have a non-zero value, otherwise it will be zero.

Example:

```0 1 0
1 0 1
0 1 0
```

In the above example, there are three vertices (0, 1, and 2) and two edges connecting them (0-1 and 1-2).

An adjacency list is a collection of linked lists where each list represents the neighbors of a particular vertex. The size of the list is equal to the number of vertices in the graph.

Example:

```0 -> 1 -> NULL
1 -> 0 -> 2 -> NULL
2 -> 1 -> NULL
```

In the above example, vertex 0 has an edge with vertex 1. Vertex 1 has edges with vertices 0 and 2. And vertex 2 has an edge with vertex 1.

## Graph Implementation in Java

In Java, a graph can be implemented using various data structures. One common approach is to use an adjacency list representation using a HashMap or an ArrayList.

Example:

```import java.util.*;

class Graph {

public Graph() {
adjacencyList = new HashMap<>();
}

public void addEdge(int source, int destination) {
List neighbors = adjacencyList.getOrDefault(source, new ArrayList<>());
}

public List getNeighbors(int vertex) {
return adjacencyList.getOrDefault(vertex, new ArrayList<>());
}
}

public class Main {
public static void main(String[] args) {
Graph graph = new Graph();

System.out.println("Neighbors of vertex 1: " + graph.getNeighbors(1));
}
}
```

In the above code snippet, we define a class named Graph, which uses a HashMap to store the adjacency list. The addEdge() method is used to add an edge between two vertices, and the getNeighbors() method returns the neighbors of a given vertex.

## Conclusion

A graph is a fundamental data structure that allows us to represent relationships between entities. In this article, we discussed the concept of graphs in the context of Java programming language.

We explored different representations of graphs such as adjacency matrix and adjacency list. Additionally, we provided an example implementation of a graph using an adjacency list representation in Java.

To summarize, understanding graphs and their implementations in Java is important for solving various real-world problems that involve relationships between entities.