我现在正在从我的教科书上做一个“泛型类”练习,尝试使用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方法,我似乎无法添加任何图形。
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)
有谁知道这是为什么?我似乎无法让它工作,我很难过。既没有创建
答案 0 :(得分:1)
不确定。将东西放在方括号中的语法就像你刚才所做的那样。我发现初始化HashSet
的最简单方法是使用Arrays.asList
静态方法。我会写这样的东西。
g.addNode(5, new HashSet<Integer>(Arrays.asList(5, 3, 7)));
答案 1 :(得分:0)
我必须同意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);