0

I am retrieving each and every value of a single record and copying it into another array variable and setting array using a bean class and then adding that bean class to an arraylist.While I am trying to print it shows only the last record repeatedly

try{
    st=con.createStatement();
    rs=st.executeQuery("select * from data");
    while(rs.next()){
        DataBean db=new DataBean();
        for(int i=1;i<=tNumber;i++){
            a[i]=rs.getFloat(i);
        }
        db.setArray(a);
        al.add(db);
   }
} finally {
    ...
} 
user3534517
  • 121
  • 1
  • 2
  • 8

2 Answers2

3

The last entry is stored in the array repeatedly because you are storing the same object multiple times. This is a very common error - it happens when you write code that looks like this:

MyObject obj = new MyObject();
List<MyObject> list = new ArrayList<MyObject>();
while (haveMoreEntries()) {
    obj.setName(readName());
    obj.setAddress(readAddress());
    list.add(obj);
}

The problem with the code above is that it keeps adding the same object repeatedly. The fix is to move the call of the constructor into the loop, like this:

List<MyObject> list = new ArrayList<MyObject>();
while (haveMoreEntries()) {
    MyObject obj = new MyObject();
    obj.setName(readName());
    obj.setAddress(readAddress());
    list.add(obj);
}

In your case, the problem is the shared array a: you created it once, and then you call db.setArray(a); repeatedly. You should move the creation of a into the while loop, or better yet, change db.setArray to make a copy of the array.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • If i have created it once and repeatedly calling then is there any other alternative to do that – user3534517 Apr 28 '14 at 10:38
  • @user3534517 Change `db.setArray` to make a copy of the array that you pass, rather than storing the array: inside `setArray` make a new array of floats, and copy the items from the array that you pass in. – Sergey Kalinichenko Apr 28 '14 at 10:45
0

The bean object has to be local. I guess in your case you would have made it global which is creating the problem.