• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with ArrayList

 
shukla raghav
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in my problem i need to pass an arrayList to the constructor of an object in the following manner




Here is the contructor of the Question object


now when i call getPCID() after calling the pcid.clear() (shown in former code section) i get empty Arraylist; what do i do? do i need to clone.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are passing the List to the Question constructor, then clearing it. It is the same List. Calling clear on one reference will clear the List, and all other references will see the same List. Now empty.
 
Tarique Islam
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pcid.clear() will remove all the elements of pcid.
By the time you call getPCID() the ArrayList is already empty, since you are clearing it first.
Hope it helps.
 
shukla raghav
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks alot, i think i need to reinitialize the pcid everytime instead of clearing it.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you passing the same List many times in the first place? Does it contain data which all instances need? If so, pass the List, then use the "bulk" methods of the List interface to populate Lists which are fields of the Question class. You would want something to add all the elements of one List to the other List.
 
Rahul P Kumar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shukla raghav wrote:thanks alot, i think i need to reinitialize the pcid everytime instead of clearing it.

If you want to work with same pcid object rather than creating a new object in each loop, then make deep copy of pcid in Question class. In constructor, you create new arraylist, assign it to pcid and then pass pc as an argument to it.
 
shukla raghav
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks i got it..
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done

I think Shukla Rahgav's solution and mine would both have given you the same result.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic