我嘗試刷新我的Java技能。但是現在我堅持一個hashmap。我沒有得到正確的對象。這是我的示例代碼:Java:通過鍵從一個Hashmap獲取對象
public class Sample {
private static Map<String, Map<String, String>> peaks = new HashMap<String, Map<String, String>>();
private final String name;
public Sample(String name) {
this.name = name;
this.peaks = new HashMap<String, Map<String, String>>();
}
public static Map<String, Map<String, String>> getPeaks() {
return peaks;}
public static void addPeak(String peakName, String value) {
Map<String, String> peak = new HashMap<String, String>();
peak.put("value", value);
peaks.put(peakName, peak);
}
}
public class Main {
static Map<Integer, Sample> sample = new HashMap<Integer, Sample>();
public static void main(String[] args) {
Sample sam = new Sample("Test1");
sample.put(1, sam);
sample.get(1).addPeak("A", "1");
sam = new Sample("Test2");
sample.put(2, sam);
sample.get(2).addPeak("B", "123");
System.out.println(sample.get(1).getPeaks().toString());
System.out.println(sample.get(2).getPeaks().toString());
System.out.println(sample.get(4).getPeaks().toString());
}
}
每次輸出爲:{B = {值= 123}}
不知哪一部分是錯誤的。我錯過了什麼?
你會得到什麼?請粘貼您的輸出。 – Freak
只需刪除靜態。 – ujvl
@freak它在那裏,埋葬。 Joko,請將輸出作爲一個單獨的塊發佈,而不是將其隱藏在評論中。 – chrylis