dcsimg
Converting a 2D ArrayList to Array
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Ganesh_Shankar
Posted On:   Friday, March 18, 2005 12:24 PM

Hello All, I have a 2D ArrayList populated from a ResultSet. Created thusly: ArrayList rowArray = new ArrayList(); ArrayList rowsetArray = new ArrayList(); /* ...some sql */ //grs is the resultset. while (grs.next()){ rowArray.clear(); rowArray.add(grs.getString(1)); rowArray.add(grs.getString(2)); rowsetArray.add(rowArray.clone()); } I know the values are really floats. Now how do I get them out into an array? Do I have to iterate through the 2D ArrayList and do individual casts? How do I iterate through a 2D ArrayList? The closest answer I came upon was this (http://forum.java.sun.com/thread.jspa?threadID=509717&messag   More>>

Hello All,

I have a 2D ArrayList populated from a ResultSet. Created thusly:
ArrayList rowArray = new ArrayList();
ArrayList rowsetArray = new ArrayList();
/*
...some sql
*/
//grs is the resultset.

while (grs.next()){
rowArray.clear();
rowArray.add(grs.getString(1));
rowArray.add(grs.getString(2));
rowsetArray.add(rowArray.clone());

}

I know the values are really floats. Now how do I get them out into an array? Do I have to iterate through the 2D ArrayList and do individual casts? How do I iterate through a 2D ArrayList?
The closest answer I came upon was this (http://forum.java.sun.com/thread.jspa?threadID=509717&messageID=2420305)
but had compilation problems with the final answer.

Thanks for any help.

gshankar

   <<Less

Re: Converting a 2D ArrayList to Array

Posted By:   Eric_Hubbard  
Posted On:   Tuesday, March 22, 2005 06:05 PM

What is your inner dimension an ArrayList in the first place? You know how many columns you are going to need. Why not:


ResultSet grs = null;
ArrayList rows = new ArrayList();
while(grs.next()) {
float row[] = {grs.getFloat(1), grs.getFloat(2) };
rows.add(row);
}


Now you don't have any casts to worry about at all. And you've saved memory by not overusing ArrayList on every row.
Once you want to convert it to a float[][] you can just... and check it... your saving memory again by reusing the inner arrays from above.. just moveing pointers around and you aren't haven't to nest the loop.



float data[][] = new float[2][rows.size()];
int rowNum =0;
Iterator i = rows.iterator();
while(i.hasNext()) {
float row[] = (float[]) i.next();
data[rowNum] = row;
rowNum ++;
}


disclaimer: I didn't run it!
About | Sitemap | Contact