A more flexible solution might use a HashMap instead of a List. This way you can store the column names as keys, which makes retrieving values easier and more transparent.
//declare a HashMap
Map<String,Object> hMap = new HashMap<String,Object>();
public void populateColumns(ResultSet rs) {
try{
while(rs.next()){
for (int i=1;i<=rs.getMetaData().getColumnCount();i++) {
Object obj=rs.getObject(i); //get the value for whatever column the result has
hMap.put(rs.getMetaData().getColumnName(i), obj);
} }
}catch (Exception e) {
//handle the exception
}
}
Note that if you want special handling for some database types /Java types, you can use the instanceof operator.
for (int i=1;i<=rs.getMetaData().getColumnCount();i++) {
Object obj=rs.getObject(i); /
if(obj instanceof String) //if obj is a String
hMap.put(rs.getMetaData().getColumnName(i), new String(((String)obj).getBytes("UTF-8"),"UTF-8"));
else //for every other objects
hMap.put(rs.getMetaData().getColumnName(i), obj);
UPDATE:
To get the output like you want try this
public void populateColumns(ResultSet rs) {
List<Object> list = new ArrayList<Object>();
int colCount;
try{
while(rs.next()){
colCount = rs.getMetaData().getColumnCount();
for (int i=1;i<=colCount;i++) {
Object obj=rs.getObject(i); //get the value for whatever column the result has
list.add(obj);
}
}
}catch (Exception e) {
//handle the exception
}
//
List<Object> sortedByCol = new ArrayList<Object>();
for(int j=0; j<colCount;j++){
for(int i=j; i<list.size(); i+=colCount){
sortedByCol.add(list.get(i));
}
}
For input like
col a col b col c
1 row 1 2 3
2 row 1 2 3
your output list (sortedByCol) will have
1, 1, 2, 2, 3, 3