// Stephanie's class notes. // sorely missing comments and docstrings. sorry. // Graph implemented with HashMap // Note: I have implemented the graph as a digraph. If you want to connection // node A to node B, it puts in an edge from A to B, but not the corresponding // edge from B to A. import java.util.*; public class Graph2 { private ArrayList nodes; public static class GraphNode { private HashMap neighbors; String label; public GraphNode() { this.neighbors = new HashMap(); this.label = ""; } public GraphNode(String label) { this.neighbors = new HashMap(); this.label = label; } public void connectTo( String direction, GraphNode other ) { this.neighbors.put( direction, other ); } public String toString() { String ret = this.label + ":"; for (String dir: this.neighbors.keySet()) { GraphNode n = this.neighbors.get( dir ); ret += " " + n.label + "(" + dir + ")"; } return ret; } } // end class GraphNode public Graph2() { nodes = new ArrayList(); } public void connect( GraphNode fromNode, GraphNode toNode, String direction ) { if (! this.nodes.contains( fromNode )) this.nodes.add( fromNode ); if (! this.nodes.contains( toNode )) this.nodes.add( toNode ); fromNode.connectTo( direction, toNode ); } public void printAll() { for (GraphNode n: nodes) System.out.println( n ); } public static void main( String[] args ) { Graph2 g = new Graph2(); GraphNode n1 = new GraphNode( "n1" ); GraphNode n2 = new GraphNode( "n2" ); GraphNode n3 = new GraphNode( "n3" ); g.connect( n1, n2, "east" ); g.connect( n3, n2, "west" ); g.printAll(); } }