We have learnt about Generic class in Java. We can also use them to code for Graph in Java. The Graph Class is implemented using HashMap in Java. As we know HashMap contains a key and a value, we represent nodes as keys and their adjancency list in values in the graph.
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax.
// To create an instance of generic class BaseType <Type> obj = new BaseType <Type>() Note: In Parameter type, we cannot use primitives like 'int','char' or 'double'.
Below is the implementation of the above approach:
Graph: 0: 1 4 1: 0 2 3 4 2: 1 3 3: 1 2 4 4: 0 1 3 The graph has 5 vertex The graph has 7 edges. The graph has an edge between 3 and 4. The graph does not contain 5 as a vertex.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.