HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Module for building swing tables

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
tablesmodulebuildingswingfor

Problem

I have a module that builds swing tables based on an Object[][], then I have another module that queries an SQLite database and returns a ResultSet.

I have written a method that converts the ResultSet to an ArrayList first, then further into an Object[][]. The reason I do it this way is because you cannot get the row count from the ResultSet without iterating over it.

I'm wondering if there is a more efficient way to build my Object[][] from the ResultSet without having to iterate over the data twice.

Here is the method that performs the conversion:

public Object[][] executeQuery(String query) throws SQLException{
    ResultSet rs = getResultSet(query);
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int columnCount = rsMetaData.getColumnCount();
    ArrayList result = new ArrayList();
    Object[] header = new Object[columnCount];
    for (int i=1; i <= columnCount; ++i){
        Object label = rsMetaData.getColumnLabel(i);
        header[i-1] = label;
    }
    while (rs.next()){
        Object[] str = new Object[columnCount];
        for (int i=1; i <= columnCount; ++i){
            Object obj = rs.getObject(i);
            str[i-1] = obj;
        }
        result.add(str);
    }
    int resultLength = result.size();
    Object[][] finalResult = new Object[resultLength][columnCount];
    finalResult[0] = header;
    for(int i=1;i<resultLength;++i){
        Object[] row = result.get(i);
        finalResult[i] = row;
    }
    return finalResult;
}

Solution

Well, you could just call the toArray method of your list to transform the list into an array. Or even better, you could make the table model use a List rather than an Object[][], which would avoid the unnecessary conversion.

Context

StackExchange Code Review Q#7690, answer score: 10

Revisions (0)

No revisions yet.