我现在正在做课本上的“泛型类”练习,试图使用HashMap作为底层结构来实现Graph数据结构,键是Graph中的节点,键的值是该节点相邻节点的HashSet。代码的开头如下所示:
public class Graph <T> {
public HashMap<T, HashSet<T>> foo_graph;
//... Code ...
我必须提一下,HashSet中的键和值必须是相同的类型,这就是T占位符的原因。写完我所有的方法后,我试图用静态void main
块来测试这一点,但是每当我尝试打印Graph(它已经给了我一个工作的ToString方法)时,Eclipse总是给我NullPointerExceptions
:
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在我的静态无效测试块的addNode行告诉我:
The method addNode(Integer, HashSet<Integer>) in the type Graph<Integer> is not applicable for the arguments (int, int, int, int)
有人知道这是为什么吗?我只是似乎无法让它工作,我被难倒了。既没有创造一个
当然。像你这样把东西放在方括号里的语法并不存在。我发现初始化HashSet
的最简单方法是使用Array. asList
静态方法。我会写这样的东西。
g.addNode(5, new HashSet<Integer>(Arrays.asList(5, 3, 7)));
我必须同意Eclipse。你不能这样做:
g.addNode(5, [5,3,7]);
Java不会知道[5,3,7]
是如何神奇地变成HashSet的。
你能做的是:
HashSet<Integer> set = new HashSet<>();
set.add(5);
set.add(3);
set.add(7);
g.addNode(5, set);