我在此結構中具有嵌套Hashmap:HashMap<Integer,HashMap<Integer, Integer>>
。我試圖把數據按以下順序:將整數放入Java中的嵌套Hashmap中
{
item_id1 -> { {user_id1 -> rating} , {user_id2 -> rating} ...}
item_id2 -> ...
...
}
的問題是錯誤的user_id
被插入錯誤的item_id
,從而使錯誤的評級。我認爲內部HashMap的對象引用有問題,但我不確定。
public HashMap<Integer, HashMap<Integer, Integer>> getUserRating() throws SQLException {
HashMap<Integer,HashMap<Integer, Integer>> ratings =
new HashMap<Integer,HashMap<Integer, Integer>>();
String query = "SELECT * FROM rating";
resultSet = statement.executeQuery(query);
Integer rating;
Integer user;
Integer item;
HashMap<Integer,Integer> innerHashMap = null;
while(resultSet.next()) {
item = resultSet.getInt(2);
user = resultSet.getInt(1);
rating = resultSet.getInt(3);
if(innerHashMap == null) {
innerHashMap = new HashMap<Integer,Integer>();
}
innerHashMap.put(user, rating);
ratings.put(item,innerHashMap);
}
// item_id = 400 , user_id = 44490. Should print rating = 4, but prints 2
System.out.println(ratings.get(400).get(44490));
return ratings;
}
步調與調試器。 – Kon 2015-04-03 14:53:01
提示:你調用了多少次'innerHashMap = new HashMap();'?你是否每個項目調用一次? –
2015-04-03 14:55:31
@JB Nizet好的,我明白你的觀點。假設item_id是有序的,我現在只創建一個新的內部HashMap實例,如果有一個新的項目。但是現在我在'innerHashMap.put(user,rating);' – user2097519 2015-04-03 15:04:24