Adjacency List Representation For A Graph in Java

Swathi acharya
2 min readJun 3, 2021

Hey there,

In this article, I have explained the code, taking above graph as an example to implement graph in java using Adjacency List.

So, shall we deep dive…

Here, I have created an EdgeNode class that represents the way we want to store data i.e. destiny Vertex in Integer Format and Weight between Source and Destiny Vertex also in Integer Format.

Main Method Code

In the main method, the data structure Array List of Linked List has been initialized. The main Method further calls the static method addAdj to add adjacency List and display method to display the graph.

addAdj Method Code

Static method addAdj will take two parameters, one is Linked List and another one is the source. For-Loop will take the destiny and weight value from the user and these EdgeNodes with destiny and weight value is added to the Linked List.

Display Method

This static method displayis used to print the value of adjacency List.

After running the code, we can see the output as below image.

Final Output

Github Link for the complete code is given below, have a look at it.

Conclusion

You’ve made it this far, congratulations! In this article you have learned about:

  • How to implement graph in java.

If you liked this article, share it with everyone! 😄

Happy Codding!

Thank you! 😃

--

--