aspose file tools*
The moose likes Beginning Java and the fly likes problem with ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem with ArrayList" Watch "problem with ArrayList" New topic
Author

problem with ArrayList

shukla raghav
Ranch Hand

Joined: Aug 03, 2008
Posts: 200
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

Joined: Oct 13, 2005
Posts: 39879
    
  28
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

Joined: Oct 14, 2009
Posts: 5
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

Joined: Aug 03, 2008
Posts: 200
thanks alot, i think i need to reinitialize the pcid everytime instead of clearing it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39879
    
  28
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

Joined: Sep 26, 2009
Posts: 188
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

Joined: Aug 03, 2008
Posts: 200
thanks i got it..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39879
    
  28
Well done

I think Shukla Rahgav's solution and mine would both have given you the same result.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: problem with ArrayList