1

I need to add a ResultSet to a list of lists. The string passed to the method is an SQL select statement. The DB connection methods work perfectly with all other methods in this class so that's not the problem here. I know I can replace some of the ArrayList declarations with List but I don't think that matters in this case.

public static ArrayList<ArrayList> selectStatement(String string) throws SQLException {
    ArrayList<ArrayList> listOfLists = null;
    ArrayList list;
    String[] record = null;
    try {
        rs = null;
        dBConnectionOpen();
        rs = st.executeQuery(string);
        ResultSetMetaData metaData = rs.getMetaData();
        int columns = metaData.getColumnCount();
        while (rs.next()) {
            list = null;
            record = new String[columns];
            for (int i = 1; i < columns; i++) {
                record[i - 1] = rs.getString(i);
            }
            list = new ArrayList(Arrays.asList(record));
            listOfLists.add(list);
        }
    } catch (Exception e) {
    } finally {
        dBConnectionClose();
    }
    return listOfLists;
}

I have done this before, but for some reason it just won't work this time. What am I missing here?

1 Answers1

6

You initialize listOfLists with null value. Try instantiating it from the beginning:

ArrayList<ArrayList> listOfLists = new ArrayList<ArrayList>();

Also, it would be better:

  • Use List interface instead of plain ArrayList class implementation
  • Use List<String> instead of raw List.
  • Instead of using String[] record, save the data directly in the List<String>.
  • Keep the variable scope as short as possible. List<String> list can be directly inside the while loop.

Knowing this, the code can change to:

List<List<String>> listOfLists = new ArrayList<List<String>>();
...
while (rs.next()) {
    List<String> list = new ArrayList<String>();
    for (int i = 1; i < columns; i++) {
        list.add(rs.getString(i));
    }
    listOfLists.add(list);
}

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332