Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Vector and JDBC problem?

 
deepak mag
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am looping through a ResultSet to set properties of an Class(cl). Then I add each class to the vector(vt) by casting the cl into Object. But when I try to retrieve elements from the vector. I only get one element as though all the elements in the vector are occupied by only one element.
Tell me how to retain the values(Objects) in the vector?
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please post portions of your code where you are doing the key portions ie.
set cl values from resultset, adding the class to the vector and reading the vector.
any thing else that may be in question.
 
deepak mag
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I set the properties and load the vector
aud is an Object
vt_aud is the vector
while(rs.next())
{
aud.setFirstName(rs.getString(1));
aud.setLastName(rs.getString(2));
aud.setEmail(rs.getString(3));
vt_aud.add((Object)aud);
}
To retrive
for(int i=0;i<vt_aud.size();i++)>
{
aud = (audience)vt_aud.elementAt(i);

firstname = aud.getFirstName();
lastname = aud.getLastName();
email = aud.getEmail();
System.out.prinln(firstname);
}
The problem is it prints only the last record of the resultSet.
Thanks for help.
DM
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try adding aud = new WhateverClassAudIs(); as the first statement inside the while() loop.
I made the same mistake once and ended up with 50 times the same entry in the Vector. What happens is that not actual Objects are stored, but references to Objects. What you are doing here is creating a single Object, then changing it all the time. The reference you store is always the same, so each time you retrieve it you get the same Object back.

while(rs.next())
{
aud = new Aud();
aud.setFirstName(rs.getString(1));
aud.setLastName(rs.getString(2));
aud.setEmail(rs.getString(3));
vt_aud.add((Object)aud);
}
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is fairly simple once you realize that Java only stores references to objects in collections such as Vector. If you want to store several different objects in the Vector, you need to make sure each one is a separate object, not just the same object re-used each time. Try this version:

or, if you have control over the "audience" class, you can add a constructor and simplify the loop:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic