rivu
rivu

Reputation: 2514

Java Arraylist clearing : how clear() works

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

Answers (4)

Atul Kumbhar
Atul Kumbhar

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

Ravi K Thapliyal
Ravi K Thapliyal

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

Ashalynd
Ashalynd

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

Jigar Joshi
Jigar Joshi

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

Related Questions