Reputation: 2514
I have a 2D list of objects mypath List<List<Object>> mypath = new ArrayList<List<Object>>();
. Suppose I have following lines of code
mypath.add(temppath);
System.out.println("mypath: "+mypath.get(mypath.size()-1));
temppath.clear();
System.out.println("mypath: "+mypath.get(mypath.size()-1));
I see a list of objects from first print statement, but an empty list from second print. It appears when I clear temppath, that element of mypath also gets cleared. Is there a way to circumvent this problem? Can I clear temppath, without clearing the last element of mypath?
Upvotes: 2
Views: 278
Reputation: 1083
Rivu,
You are clearing temppath, but not removing it from mypath. Hence, on second attempt you are referring to temppath again, which is blank.
if you want to remove temppath use
mypath.remove(temppath);
instead of
temppath.clear();
Upvotes: 0
Reputation: 51711
If you're trying to reuse temppath
to keep adding new List
of elements to mypath
, create a new List
instance instead of calling clear()
on it.
// temppath.clear();
temppath = new ArrayList<Object>();
List#clear()
does not give you a new List
instance and you end up clearing the same list you just added to mypath
. Only call clear()
to dispose off elements.
Upvotes: 1
Reputation: 12563
When you add temppath to mypath, you don't create a new object, you add a reference to an existing one. Therefore, everything what you do with this object will be reflected in any place where it's referenced.
One possible solution for this problem will be to create a copy of temppath and add it to mypath.
Upvotes: 5
Reputation: 240898
because both are referring to same Object
in heap, make it like
mypath.add(new ArrayList<Object>(temppath));
this will create copy of temppath
if it is not harmful to your app
Upvotes: 4