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); }
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.