• Post Reply Bookmark Topic Watch Topic
  • New Topic

Bean object in Vector question (confused)  RSS feed

 
W Stoddard
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below will not load the vector properly unless I instantiate CashBean within the while loop.
When I extract the bean from the vector I only get values for the last instance of the bean for all of the vector indexes.
It works fine if the caBean object is created whithin the while loop.
Why must I create a new object each time before it is added to the vector?

Vector errorList = new Vector();
CashBean caBean = new CashBean();
while (rs.next()) {
ctBean.setAccountName (rs.getString("ACCT_NAM"));
errorList.add(ctBean);
}

-------------------------------------------------------------------------
This code works fine

Vector errorList = new Vector();
while (rs.next()) {
CashBean caBean = new CashBean();
ctBean.setAccountName (rs.getString("ACCT_NAM"));
errorList.add(ctBean);
}
 
Billybob Marshall
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because when you add the object, it doesn't copy it - just a reference to it. So changing the object has the effect of changing what was just added, hence all references added are pointing at the same object with the final state.
 
W Stoddard
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see, that makes sense now !

Thanks for the explanation !
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of those rare moments when you're reminded of the existence of pointers in Java (albeit under the hood).
 
Jeroen Stroom
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think there is a small type error in your code.
caBean is not ctBean.
 
W Stoddard
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good observation ! I shortened the names for this post and typoed the bean names.
Thanks again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!