Add a hashmap to an array of hashmaps

I have the following code:

    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++;
    }

The idea is to have the output be like this.. and I'll use PHP as an example:

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

And so on.. but, what I get is a list of 10 HashMaps that all contain the same username,register_ip value. What are my options?

Answers


That is because you're adding the same botInfo HashMap to your List. What you would want to do is create a new HashMap inside your while loop, add elements to it and finally add this map to your list. What you would want to do is something like this:

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++;
}

Need Your Help

Determine Project References to mscorlib

c# asp.net reference mscorlib

Hey folks, I've got an ASP.NET web site project that for some reason is insisting on referencing both mscorlib 1.0.5 and mscorlib 2.0, and I can't figure out why.

jQuery : reserve key this, and ambiguous cases

jquery

I´m littel confused with this reserve key and cases caused errors. Here a sample code where this causes errors.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.