将Integer放入Java中的嵌套Hashmap中

时间:2015-04-03 14:50:45

标签: java hashmap nested object-reference

我在这个结构中有一个嵌套的Hashmap:HashMap<Integer,HashMap<Integer, Integer>>。我试图按此顺序放置数据:

{
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;

}

3 个答案:

答案 0 :(得分:1)

谢谢@JB Nizet。这有效:

    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;

}

答案 1 :(得分:0)

您应该尝试在每次迭代时重新创建一个新的innerHashMap。

实际上你只有一个,所以你混合了它的值。

答案 2 :(得分:-1)

删除if条件

if(innerHashMap == null) {
    innerHashMap = new HashMap<Integer,Integer>();
}

由于每个商品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);
}