[英]Put Integer in a nested Hashmap in Java
I have a nested Hashmap in this structure: HashMap<Integer,HashMap<Integer, Integer>>
. 我在此结构中有一个嵌套的Hashmap: HashMap<Integer,HashMap<Integer, Integer>>
。 I'm trying to put data in this order: 我试图按此顺序放置数据:
{
item_id1 -> { {user_id1 -> rating} , {user_id2 -> rating} ...}
item_id2 -> ...
...
}
The problem is that wrong user_id
gets inserted into wrong item_id
, thus giving wrong rating. 问题是错误的user_id
插入了错误的item_id
,因此给出了错误的评分。 I think there is a problem with the object reference of the inner HashMap, but I'm not sure. 我认为内部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;
}
Thanks @JB Nizet . 谢谢@JB Nizet。 This works: 这有效:
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(ratings.get(item) == null) {
innerHashMap = new HashMap<Integer,Integer>();
}
innerHashMap.put(user, rating);
ratings.put(item,innerHashMap);
}
// item_id = 400 , user_id = 44490. Should print rating = 4
System.out.println(ratings.get(400).get(44490));
return ratings;
}
You should try to re-create a new innerHashMap on each iteration. 您应该尝试在每次迭代中重新创建一个新的innerHashMap。
Actually you just have one so you mix the values in it. 实际上,您只有一个,因此您可以在其中混合值。
Remove if
condition if
有条件则删除
if(innerHashMap == null) {
innerHashMap = new HashMap<Integer,Integer>();
}
Since you need a new HashMap for each item id , So You can create new innerHashMap
every time 由于您需要为每个项目id创建一个新的HashMap,因此您可以每次创建新的innerHashMap
while(resultSet.next()) {
item = resultSet.getInt(2);
user = resultSet.getInt(1);
rating = resultSet.getInt(3);
innerHashMap = new HashMap<Integer,Integer>(); <--- New Instance every time
innerHashMap.put(user, rating);
ratings.put(item,innerHashMap);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.