Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a Graph using a HashMap

Tags:

java

graph

I'm new to Java, so please keep that in mind before getting trigger happy down-voting. I'm familiar with the popular implementation of a graph of integers using an array.

Graph{
 int vertices;
 LinkedList<Integer>[] adj;

Graph(int vertices){
   this.vertices = vertices;
   adj = new LinkedList<>();
   for(int i= 0; i <vertices; i++){
      adj[i] = new LinkedList(); 
   }
}

However this implementation is best suited to a graph of integers. In case I want to implmentation graph of Characters, this implemetation doesn't render itself directly usable. So I tried implementing using a HashMap.

public class Graph {
    int vertices;
    HashMap<Character, LinkedList<Character>> adj;


    Graph(int item){

       this.vertices = item;
       adj = new HashMap<>();

    }
}

Where I'm a little stuck syntactically with Java is adding keys and values to this HashTable. What I'm trying to do is implement this method.

public void add(Character a, Character b){

            if (adj.containsKey(a)){

               //get a reference to the existing linked list
               //add to the existing LinkedList
            }else{

               //create a new LinkedList and add to it.
            }

        }
    }

I could use some help with the incomplete add method as also how to iterate through the this adj HashMap once the graph is constructed.

like image 663
Zeus Avatar asked Mar 13 '26 16:03

Zeus


1 Answers

Since your question is only about syntax, you can do something like this:

public void add(Character a, Character b){

        if (adj.containsKey(a)){

           //get a reference to the existing linked list
           LinkedList<Character> l = adj.get(a);

           //add to the existing LinkedList
           //You need to do a null check here to make sure (l != null)
           l.add(b)
        }else{

           //create a new LinkedList and add to it.
           LinkedList<Character> l = new LinkedList<Character>();
           l.add(b);
           adj.put(a, l);
        }

    }
}
like image 181
Atri Avatar answered Mar 17 '26 03:03

Atri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!