Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding ArrayList to TreeMap within a while cycle

I'm retrieving data from a table in a database and add the whole row to a TreeMap.

I'm using the following code:

ArrayList<String> listaValores = new ArrayList();
TreeMap<Integer, ArrayList> tmValores = new TreeMap<>();

(...)

    while (rs.next()) 
    {
        listaValores.clear();
        for(int i=2; i<=ncolunas; i++)
        {
            listaValores.add(rs.getString(i));
        }
        tmValores.put(rs.getInt(1), listaValores);   
    }

My TreeMap keys are inserted fine but the values are always repeated as the values from the last line as a result from the SELECT * FROM Table query.

So if my table is:

id | name | last name | 
1  | joe  | lewis     | 
2  | mark | spencer   | 
3  | mike | carter    | 
4  | duke | melvin    |

My TreeMap contains:

1=> duke, melvin  
2=> duke, melvin  
3=> duke, melvin  
4=> duke, melvin

Instead of (as I wanted)

1=> joe, lewis 
2=> mark, spencer 
3=> mike, carter 
4=> duke melvin

Can anyone point me out where is the problem?

like image 600
dazito Avatar asked Jul 29 '26 22:07

dazito


2 Answers

I believe you have to reassign the value of listaValores.

Simply change

 listaValores.clear();

to

 listaValores = new ArrayList<String>();
like image 197
Konstantin Yovkov Avatar answered Aug 01 '26 12:08

Konstantin Yovkov


Objects in Java are passed around as references, so you are in fact adding the same list for all the keys in your map.

Since you clear it at every step and then add some values to it, it will contain just the last row, after the while loop has finished.

What you really want to do is to create an instance of ArrayList for every row and add that to your map, instead of clearing the values in the old one:

while (rs.next()) 
{
   listaValores = new ArrayList<String>();

   for(int i = 2; i <= ncolunas; i++)
   {
       listaValores.add(rs.getString(i));
   }

   tmValores.put(rs.getInt(1), listaValores);   
}
like image 24
Ștefan Avatar answered Aug 01 '26 13:08

Ștefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!