Java: how to represent graphs?

Nick Heiner picture Nick Heiner · Nov 15, 2009 · Viewed 120.1k times · Source

I'm implementing some algorithms to teach myself about graphs and how to work with them. What would you recommend is the best way to do that in Java? I was thinking something like this:

public class Vertex {

    private ArrayList<Vertex> outnodes; //Adjacency list. if I wanted to support edge weight, this would be a hash map.

    //methods to manipulate outnodes
}

public class Graph {
    private ArrayList<Vertex> nodes;
    //algorithms on graphs
}

But I basically just made this up. Is there a better way?

Also, I want it to be able to support variations on vanilla graphs like digraphs, weighted edges, multigraphs, etc.

Answer

bhspencer picture bhspencer · Feb 13, 2016

Each node is named uniquely and knows who it is connected to. The List of connections allows for a Node to be connected to an arbitrary number of other nodes.

public class Node {
    public String name;
    public List<Edge> connections;
}

Each connection is directed, has a start and an end, and is weighted.

public class Edge {
    public Node start;
    public Node end;
    public double weight;
}

A graph is just your collection of nodes. Instead of List<Node> consider Map<String, Node> for fast lookup by name.

public class Graph {
    List<Node> nodes;
}