以下是CompleteGraph的代码,它基本上接受节点列表,然后接收所有节点的邻接/边缘。有一个名为getAdj
的函数会抛出IllegalState,因为根据逻辑,图形仍在构建中,并且即使在用户完全构造之前,use也调用了此函数。这是否是使用IllegalState的正确决定?
public class CompleteGraph<T> {
private final Map<T, HashMap<T, Double>> graph;
private Set<T> nodes;
public CompleteGraph() {
graph = new HashMap<T, HashMap<T, Double>>();
}
public void addNodes (Set<T> nodes) {
if (nodes == null) throw new NullPointerException("The node cannot be null.");
if (nodes.size() == 0) throw new NullPointerException("The size of node cannot be zero.");
this.nodes = nodes;
}
public void addEdges (T nodeId, Map<T, Double> addEdges) {
if (!nodes.contains(nodeId)) throw new NoSuchElementException("The source node: " + nodeId + " does not exist.");
for (T node : addEdges.keySet()) {
if (!nodes.contains(node)) throw new NoSuchElementException("The target node: " + nodeId + " not exist.");
}
graph.put(nodeId, (HashMap<T, Double>) addEdges);
}
public Map<T, Double> getAdj (T nodeId) {
if (!nodes.contains(nodeId)) throw new NoSuchElementException("The node " + nodeId + " does not exist.");
if (!graph.containsKey(nodeId)) throw new IllegalStateException("The graph is not populated with " + nodeId);
return graph.get(nodeId);
}
}