2016-04-30 114 views
2

我是新來的,不要在開始時殺死我。 我的代碼應該創建學生並計算他的平均成績。 一切都好,直到我試圖添加另一個學生。 來自主Map的關鍵字不同,但是來自innerMap的主題的平均值被覆蓋。JavaFX - 多維hashmap被覆蓋

如果我創造幾個學生,他們每個人都有不同的名字(主),但平均值相同(我添加了最新的)。

我'創造了這種風格包含HashMap:

Map<String, HashMap<String, Double>> mainMap = new HashMap<String, HashMap<String, Double>>(); 
Map<String, Double> innerMap = new HashMap<String, Double>(); 

和我創造了我的類的實例與此地圖獲得靜態存取權限:

private static AvgLists instance = new AvgLists(); 

public static mapClass getInstance() { 
    return instance; 
} 

在另一大類爲我放入創造方法地圖中的值:

innerMap.put(subject, grade); 
mainMap.put(key, innerMap); 

keyMap for mainMap is String with name and name of student。

另外,我爲我的語言表示歉意。 感謝您的時間!

回答

1

很難從您的代碼中知道,但由於Map似乎都是字段,所以很可能您只是爲所有學生使用單個地圖。您需要爲每個學生創建新地圖:

Map<String, Map<String, Double>> mainMap = new HashMap<>(); 

void setGrade(String studentName, String courseName, double average) { 
    // create new inner map, if there is none for this student 
    Map<String, Double> innerMap = mainMap.computeIfAbsent(studentName, s -> new HashMap<>()); 

    // add grade to map for student 
    innerMap.put(courseName, average); 
}