我正在從我的教科書中進行「通用類」練習,嘗試使用HashMap作爲底層結構實現一個Graph數據結構,並帶有鍵是圖中的節點,並且密鑰的值是與該節點相鄰的節點的HashSet。該代碼的開頭是這樣的:當它是一個HashMap的值時添加到HashSet中
public class Graph <T> {
public HashMap<T, HashSet<T>> foo_graph;
//... Code ...
不得不提的是,無論是在HashSet的鍵和值必須是同一類型,這是於T佔位符的原因。用我的方法寫出來,我想用static void main
塊測試,但是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是告訴我在ADDNODE線在我的靜態無效測試塊:
The method addNode(Integer, HashSet<Integer>) in the type Graph<Integer> is not applicable for the arguments (int, int, int, int)
有誰知道這是爲什麼?我似乎無法讓它工作,我很難過。既不創建
你們都回答這麼快......這就是爲什麼我愛的StackOverflow :) – karysto