Here is a suggestion from me for what it's worth. It uses an adjacecny matrix to represent the weight which can either be an integer or a double (not sure why anyone would want this) and then a list of vertices for the nodes.
Still anything more than this should really be using interfaces for V and E.
public class Graph <V, E> { private List<V> vertices; private E[][] adjMatrix; public void setVertices(List<V> nodes) { vertices = nodes; } public void setAdjacecnyMatrix(E[][] adjMatrix) { this.adjMatrix = adjMatrix; } public Object getNode(int index) { return vertices.get(index); } public boolean hasEdge(int srcs, int dest) { for (int v = 0; v < vertices.size(); v++) { if (adjMatrix[srcs][dest] instanceof Integer && (Integer) adjMatrix[srcs][dest] > 0) return true; if (adjMatrix[srcs][dest] instanceof Double && (Double) adjMatrix[srcs][dest] > 0) return true; } return false; } public double graphWeight() { double sum = 0; int numV = vertices.size(); for (int s = 0; s < numV; s++) { for (int v = 0; v < numV; v++) { if (adjMatrix[s][v] instanceof Double) { sum += (Double) adjMatrix[s][v]; } else if (adjMatrix[s][v] instanceof Integer) { sum += (Integer) adjMatrix[s][v]; } } } return sum; } } public static void main(String[] args) { Graph<String, Double> g = new Graph(); String[] nodes = {"A", "B", "C"}; Double[][] adjMatrix = { {0., 1., 3.}, {1., 0., 2.}, {3., 2., 0.}}; g.setVertices(Arrays.asList(nodes)); g.setAdjacecnyMatrix(adjMatrix); System.out.println("g1: " + g.graphWeight()); Graph<String, Integer> g2 = new Graph(); Integer[][] adjMatrix2 = { {0, 1, 4}, {1, 0, 2}, {4, 2, 0}}; g2.setVertices(Arrays.asList(nodes)); g2.setAdjacecnyMatrix(adjMatrix2); System.out.println("g1: " + g2.graphWeight()); }
instanceofto find out ifweightis of typeDouble, then cast it.Graphwhich defines the constraints asStringandDouble, it only makes sense to haveweightwhenTis a numeric value