2

I want to implement a graph class. I decided to represent the graph by using an adjacency map, like this:

// Option 1:

HashMap<Node<T>, List<Edge<T>>> adjacencyMap;    // not so good.

Now my question regards the best practice of this kind of structure. Isn't it a bad idea to use a Node class as the key in this map? I'm not even able to adress adjacencyMap, because the identifying value is vertex, a field of the node class.

public class Node<T> {

    private T vertex;
}

Otherwise if i map the explicit vertex (the specific value) of the nodes, i connect a vertex (value) to a list of nodes (class containing that vertices). Is this a good idea or am I running into problems?

// Option 2:

HashMap<<T>, List<Edge<T>>> adjacencyMap;    // better 

For the sake of completeness, here are the other classes:

public class Graph<T> {

    private HashMap<Node<T>, List<Edge<T>>> adjacencyMap;
}

public class Edge<T> {

    private Node<T> nodeX;
    private Node<T> nodeY;
    private double weight;
}

An obvious design choice would be to put the list of edges into the node class and just map my vertices to the node classes, but i find it a weird structure to maintain edges in nodes.

Can someone provide any kind of best practice regarding this problem?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Ipsider
  • 553
  • 1
  • 7
  • 20
  • Scott Mitchell wrote an in depth article about this process back in 2005, but he did it with C#. If you're not familiar with C#, I think you'll find it closely resembles Java in syntax. He proposes two classes for creating the Graph class and the GraphNode class. It's probably worth checking out for your project - refer to [Creating a Graph Class](https://msdn.microsoft.com/en-us/library/ms379574(v=vs.80).aspx#datastructures20_5_topic3) – ThisClark Nov 15 '15 at 17:09
  • Thanks, basically he is also implementing the list of edges within the node class. Maybe this is the best solution, it just bugs me, because it's a quite counter-intuitive approach to encapsulate the edges in the node. – Ipsider Nov 15 '15 at 18:00
  • I think it will become more intuitive when you begin implementing traversal algorithms like minimum spanning tree and Dijkstra's shortest path. If you want to add properties to your edges, you can use an object rather than the primitive int cost Scott uses. – ThisClark Nov 15 '15 at 18:09

0 Answers0