Creating Objects inside a loop.
Hello there, be easy on me as i'm not wonderful with Java, just wondering if someone could help me.
I have a program at the moment which is accessing a database, it's running a query and then storing it in a resultset object. Then i'm running a loop which gets the information out row by row using the .next method. Then this loop retreives three pieces of information using .getInt twice and .getString.
What i would like to do is create an object which stores the three pieces of information as there retrieved from the database. So say theres 15 rows in the table, i'd end up with 15 objects with the information in.
The problem i'm having is that i can't write the object declaration within the loop because i would end up defining the same object many times depending on how many rows there are.
I hope someone can help and i hope that i've made some sense. Thank you very much for any help.
[934 byte] By [
Mystic15a] at [2007-11-26 12:36:15]

> If u know exact number of records in the database
> table, create an array of objects with the size u
> require and assign the values in the loop for each
> object. I hope u know how to assign the values inside
> a loop once u create an array of objects
Even if someone doesn't know the number of records, there is always ArrayList.
> If u know exact number of records in the database
> table, create an array of objects with the size u
> require and assign the values in the loop for each
> object. I hope u know how to assign the values inside
> a loop once u create an array of objects
It sounds like the result length varies.
It would just be easier to use a list in either case.
> > If u know exact number of records in the database
> > table, create an array of objects with the size u
> > require and assign the values in the loop for each
> > object. I hope u know how to assign the values
> inside
> > a loop once u create an array of objects
>
> It sounds like the result length varies.
>
> It would just be easier to use a list in either case.
I'm not that familiar with lists as i've never used them before, however i've just managed to get it working with an array.
I can't thank you enough.
Just out of curiosity how does ArrayList work?
I can presume the number of records in the database and it should work fine, however i'd prefer not to have to.
Thanks again guys.
> Just out of curiosity how does ArrayList work?
http://java.sun.com/docs/books/tutorial/collections/index.html
ArrayList list = new ArrayList();
while(rs.next()){
list.add(new MyObject(rs.getString("")));
}