# Graph Implementation in Java using Collections

In this post, we will see graph implementation in Java using Collections for weighted and unweighted, graph and digraph.

We know that in an adjacency list representation of the graph, each vertex in the graph is associated with the group of its neighboring vertices or edges. In other words, every vertex stores a list of adjacent vertices.

For example, below is the pictorial representation for corresponding adjacency list for above graph –

## 1. Directed Graph (Digraph) Implementation –

Below is Java implementation of a digraph using Adjacency list:

Output:

(0 –> 1)
(1 –> 2)
(2 –> 0) (2 –> 1)
(3 –> 2)
(4 –> 5)
(5 –> 4)

As evident from above code, an edge is created from src to dest in the adjacency list in a digraph and if the graph is undirected, we also need to create the edge from dest to src in the adjacency list.

## 2. Weighted Digraph Implementation –

We know that in a weighted graph, every edge will have a weight or cost associated with it as shown below:

Below is Java implementation of a weighted digraph using adjacency list. The implementation is similar to that of unweighted digraph, except we’re also storing the weight infomation in adjacency list with every edge.

Output:

0 –> 1 (6)
1 –> 2 (7)
2 –> 0 (5) 2 –> 1 (4)
3 –> 2 (10)
4 –> 5 (1)
5 –> 4 (3)

Also see:

(1 votes, average: 5.00 out of 5)

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Subscribe
Notify of
Guest
abhishek kumar

Hi sir,
i need to know why you had used List<List> adj = new ArrayList();
it can be done with List = new LinkedList();
Is there any benefit of it. I’m new to java plzz reply me

Guest

Can you please explain the need for line number 38 and 39 (see unweighted one). I am unable to understand why is there a need to allocate space for each edge?
Shouldn’t it be the way that memory be allocated for the number of vertices only?

Guest