import java.util.ArrayList; import java.util.HashMap; /** * Graph represented as an edge list * @author gtowell * Created: Dec 1, 2021 */ public class EdgeList { //A node. Not clear that this class is really necessary private class Node { // the content of the node public H payload; public Node(H payl) { this.payload = payl; } public String toString() { return this.payload.toString(); } } private class Edge { // source of the edge Node from; // destination of the edge Node too; // weight of the edge double wei; /** * Constructor * Creates an edge with a weight of 1 */ public Edge(Node fr, Node t2) { this(fr, t2, 1.0); } /** * Construct an edge with the given weight * @param fr from * @param t2 to * @param w weight */ public Edge(Node fr, Node t2, double w) { this.from = fr; this.too = t2; this.wei = w; } public String toString() { return String.format("[%s->%s:%.1f]", from, too, wei); } } // Holds edges ArrayList> egLi; // Holds all of the known nodes HashMap> nodeHash; public EdgeList() { egLi = new ArrayList>(); nodeHash = new HashMap<>(); } public String toString() { StringBuffer sb = new StringBuffer(); for (Edge eg : egLi) { sb.append(eg.toString()); } return sb.toString(); } public static void main(String[] args) { EdgeList edl = new EdgeList<>(); edl.addEdge("A", "B"); edl.addEdge("A", "D"); edl.addEdge("B", "D"); edl.addEdge("C", "D"); edl.addEdge("C", "B"); edl.addEdge("C", "A"); edl.addEdge("D", "B"); System.out.println(edl); } /** * Get a node object that hash the payload. If one does not already * exist, then make one. * @param g the payload to look for * @return a Node containing the payload. */ private Node getNode(G g) { Node ret = nodeHash.get(g); if (ret == null) { ret = new Node<>(g); nodeHash.put(g, ret); } return ret; } /** * Add edge between the two given items * @param fr * @param t2 */ public void addEdge(G fr, G t2) { egLi.add(new Edge(getNode(fr), getNode(t2))); } }