0

我有以下代码:

    ResultSet rs = DB.doQuery("SELECT username,register_ip FROM users ORDER BY joined DESC LIMIT 10");
    Map<String,String> botInfo = new HashMap<String, String>();
    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();
    int c = 0;

    while(rs.next()) {
        botInfo.put("username", rs.getString("username"));
        botInfo.put("register_ip", rs.getString("register_ip"));
        myMap.add(c, botInfo);
        c++;
    }

这个想法是让输出像这样..我将使用 PHP 作为示例:

[0] => array('username' => 'someUsername', 'register_ip' => 'someIP');

依此类推.. 但是,我得到的是 10 个 HashMap 的列表,它们都包含相同的 username,register_ip 值。我有哪些选择?

4

4 回答 4

4

那是因为您将相同的botInfo HashMap 添加到列表中。您想要做的是在您的 while 循环中创建一个新的 HashMap,向其中添加元素,最后将此映射添加到您的列表中。你想要做的是这样的:

ResultSet rs = DB.doQuery("SELECT username,register_ip FROM users ORDER BY joined DESC LIMIT 10");
List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();
int c = 0;

while(rs.next()) {
    //Create a new instance of the map
    Map<String,String> botInfo = new HashMap<String, String>();

    //Add elements to the the map
    botInfo.put("username", rs.getString("username"));
    botInfo.put("register_ip", rs.getString("register_ip"));

    //Add the map to the list
    myMap.add(c, botInfo);

    //Increment your counter
    c++;
}
于 2012-09-10T06:25:32.163 回答
2
ResultSet rs = DB.doQuery("SELECT username,register_ip FROM users ORDER BY joined DESC LIMIT 10");
List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

while(rs.next()) {
    Map<String,String> botInfo = new HashMap<String, String>();
    botInfo.put("username", rs.getString("username"));
    botInfo.put("register_ip", rs.getString("register_ip"));
    myMap.add(botInfo);
}

每条记录都需要一个新HashMapbotInfo

编辑:c没用

于 2012-09-10T06:25:38.413 回答
1
ResultSet rs = DB.doQuery("SELECT username,register_ip FROM users ORDER BY joined DESC LIMIT 10");
Map<String,String> botInfo;
List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

while(rs.next()) {
    botInfo = new HashMap<String, String>();
    botInfo.put("username", rs.getString("username"));
    botInfo.put("register_ip", rs.getString("register_ip"));
    myMap.add(botInfo);
}

使用此代码..这将对您有所帮助。

于 2012-09-10T06:26:04.717 回答
0

试试这个:

ResultSet rs = DB.doQuery("SELECT username,register_ip FROM users ORDER BY joined DESC LIMIT 10");
Map<String,String> botInfo;
List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();
String[] columns = {"username", "register_ip"};

while(rs.next()) {
    botInfo = new HashMap<String, String>();
    for(int i = 0; i < columns.length; i++) {
        botInfo.put(columns[i], rs.getString(columns[i]));
    }
    myMap.add(botInfo);
}
于 2012-09-10T06:28:47.517 回答