【发布时间】:2013-10-29 01:56:51
【问题描述】:
我现在正在做我教科书中的“通用类”练习,尝试使用 HashMap 作为底层结构来实现 Graph 数据结构,其中键是 Graph 中的节点,而键的值是与该节点相邻的节点的 HashSet。代码的开头是这样的:
public class Graph <T> {
public HashMap<T, HashSet<T>> foo_graph;
//... Code ...
必须提一下,HashSet 中的键和值都必须是同一类型,这就是 T 占位符的原因。写完我所有的方法后,我正在尝试使用static void main 块进行测试,但是每当我尝试打印 Graph 时,Eclipse 都会不断给我NullPointerExceptions(它已经给了我一个有效的 ToString 方法):
public static void main(String[] args) {
Graph<Integer> g = new Graph<>();
g.addNode(5, [5,3,7]); //Trying to add 5,3,7 to the HashSet, but Eclipse is saying I can't do this.
System.out.println(g);
}
顺便说一下,这是我的 addNode 方法,我似乎也无法在 Graph 中添加任何内容。
public void addNode(T node_key, HashSet<T> node_value ) {
main_graph.put(node_key, node_value);
Eclipse 在我的静态 void 测试块的 addNode 行告诉我:
The method addNode(Integer, HashSet<Integer>) in the type Graph<Integer> is not applicable for the arguments (int, int, int, int)
有人知道这是为什么吗?我似乎无法让它工作,我很难过。既不创建一个
【问题讨论】:
-
你们都回答得这么快...这就是我喜欢 StackOverflow 的原因 :)
标签: java graph nullpointerexception hashmap hashset