aspose file tools*
The moose likes Beginning Java and the fly likes Java Collection overwrites all elements when using add() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java Collection overwrites all elements when using add()" Watch "Java Collection overwrites all elements when using add()" New topic
Author

Java Collection overwrites all elements when using add()

Marcel Jacome
Greenhorn

Joined: Feb 06, 2009
Posts: 26
Hi guys , i have a problem which has kept me banging my head against a brick wall all day. I am using a collection to store objects
so later i can display them in a rich:dataTable component.

I have an iterator in a for loop so as to initialize an object (detalle). Once an object is initialized, it gets stored in a collection
using the add(Object) method , problem is , the whole collection is overwritten by the most recent object inserted by the add() method.

It goes something like this:

Iteration 1
object detalle1 is initialized
object detalle1 is added to a collection
collection's size is one and holds object detalle1

Iteration 2
object detalle2 is initialized
object detalle2 overwrites the first slot
object detalle2 is added to an auxiliary collection
Now instead of having Collection: detalle1 , detalle2 , i have a duplicate of object detalle2 and the first object is overwritten.
collection's size is two and holds detalle2 , detalle2 (detalle1 has been overwritten)

If I continue with more iterations , the last object is added at the end , but overwrites all the rest of the objects in the collection.So i end
up with the last object all over the collection.

I tried advancing the pointer with Collection.iterator.next() to no avail. This keeps happening and I dont know what is going on.

Please Help!!!


This is the code



Thanks in advance

Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

You are using the same detalle object all along. Maybe moving "CargosAplicacionBeanDetalles detalle = new CargosAplicacionBeanDetalles();" into the for loop would solve your problem ?


[My Blog]
All roads lead to JavaRanch
Marcel Jacome
Greenhorn

Joined: Feb 06, 2009
Posts: 26
Thanks very much Christophe , your advice makes a lot of sense. i will give it a try and let you know.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38902
    
  23
And always avoid == true and == false. Use if (boo) . . . not if (boo == true). Use if (!boo) . . . not if (boo == false).
Marcel Jacome
Greenhorn

Joined: Feb 06, 2009
Posts: 26
Thanks Christophe, it solved my problem and thanks Ritchie for the advice , you are totally right. A nice day to you both.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java Collection overwrites all elements when using add()