views:

979

answers:

1

I'm building an application in Java to retrieve data from MySQL database. After executing a query I get a ResultSet and do the following to extract records:

while (rs.next())
        {
            for (int column = 1; column <= rm.getColumnCount(); column++) {
                row.add(rs.getObject(column));
            }
            result.add(row.toString());
            row.clear();
        }

where rs = ResultSet and rm = ResultSetMetaData

The problem is that I have to do result.add(row.toString()); rather than just result.add(row); (with which I'd like to create a two-dimensional ArrayList). Otherwise I get empty results.

I have tried putting row.clear(); at the beginning, before the for loop, but that results in all my results being filled with multiple instances of the last record. Just like row was not added to the result until the very end, when it's equal to the last record. Do I need to "commit" the ArrayList row before adding it as an elemt to another ArrayList? If so, how? Also, out of curiosity, why is .toString() working differently?

+1  A: 

By adding row.toString(), you're creating a new String object to add into result.

On the other hand, by adding row, you're adding the same object into result, therefore, each time row.clear() is called, it empty all the rows in result.

What you should do is to create a new row object before the for loop, and don't do row.clear(). Following is an example.

while (rs.next())
        {
   row = new ArrayList();

            for (int column = 1; column <= rm.getColumnCount(); column++) {
                row.add(rs.getObject(column));
            }

   result.add(row);
        }
Dan
OK, so basically result.add(row) works like "pass by reference", not copying the object, but just providing a reference to it?Thanks, that solved my problem :)
maciej.gryka