Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Collection overwrites all elements when using add()

 
Marcel Jacome
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are using the same detalle object all along. Maybe moving "CargosAplicacionBeanDetalles detalle = new CargosAplicacionBeanDetalles();" into the for loop would solve your problem ?
 
Marcel Jacome
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much Christophe , your advice makes a lot of sense. i will give it a try and let you know.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50225
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And always avoid == true and == false. Use if (boo) . . . not if (boo == true). Use if (!boo) . . . not if (boo == false).
 
Marcel Jacome
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Christophe, it solved my problem and thanks Ritchie for the advice , you are totally right. A nice day to you both.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic