user3534517
user3534517

Reputation: 133

Why only the last value that we are trying to add is stored in an arraylist repeatedly

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 {
    ...
} 

Upvotes: 0

Views: 2067

Answers (2)

Siddaraju Siddappa
Siddaraju Siddappa

Reputation: 23

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

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.

Upvotes: 3

Related Questions