HashMap被最后一个值覆盖

时间:2013-09-27 09:52:38

标签: java arrays collections hashmap

Statement selectStatement = connection.createStatement();
        ResultSet selectResultSet = selectStatement.executeQuery(query);
        logger.info("sql query " + selectStatement.toString());
        ResultSetMetaData rsmd = selectResultSet.getMetaData();
        int columnsNumber = rsmd.getColumnCount();
        String[] row = new String[columnsNumber];

        int ctr = 0;
        logger.info("Reading from database...");
        while(selectResultSet.next())
        {
            for(int i=0;i<columnsNumber;i++){
                row[i] = selectResultSet.getString(i+1);
            }
            System.out.println();
            dataFromQuery.put(ctr++, row);
        }
        selectResultSet.close();

从HashMap读回时,它只打印最后一行'n'次。

2 个答案:

答案 0 :(得分:3)

你缺少的是 - {while}循环中的row = new String[columnsNumber];,这实际上会导致过度编写数组对象值而你将相同的对象添加到HashMap

...
while(selectResultSet.next()){
     row = new String[columnsNumber];
     for(int i=0;i<columnsNumber;i++){
         row[i] = selectResultSet.getString(i+1);
     }
     System.out.println();
     dataFromQuery.put(ctr++, row);
}
...

答案 1 :(得分:1)

在while循环中声明行数组,以便每一行都有自己的副本,当前map中的每一行都引用相同的行数组,并被最后一个循环覆盖。