2

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?

2 Answers 2

6

I believe you have to reassign the value of listaValores.

Simply change

 listaValores.clear();

to

 listaValores = new ArrayList<String>();
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.