简体   繁体   English

Java Arraylist clearing:clear()的工作原理

[英]Java Arraylist clearing : how clear() works

I have a 2D list of objects mypath List<List<Object>> mypath = new ArrayList<List<Object>>(); 我有一个对象的2D列表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. 我从第一个print语句中看到一个对象列表,但是从第二个print中看到一个空列表。 It appears when I clear temppath, that element of mypath also gets cleared. 当我清除temppath时,mypath的元素也会被清除。 Is there a way to circumvent this problem? 有办法解决这个问题吗? Can I clear temppath, without clearing the last element of mypath? 我可以清除temppath,而不清除mypath的最后一个元素吗?

When you add temppath to mypath, you don't create a new object, you add a reference to an existing one. 将temppath添加到mypath时,不创建新对象,而是添加对现有对象的引用。 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. 解决此问题的一种可能方法是创建temppath的副本并将其添加到mypath。

because both are referring to same Object in heap, make it like 因为它们都在堆中引用相同的Object ,所以就像它一样

mypath.add(new ArrayList<Object>(temppath));

this will create copy of temppath 这将创建temppath副本

if it is not harmful to your app 如果它对您的应用程序无害

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以继续向mypath添加新的元素List ,请创建一个新的List实例,而不是在其上调用clear()

// 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 . List#clear() 给你一个新的 List实例,你最终结算刚才添加到同一列表mypath Only call clear() to dispose off elements. 只调用clear()来处理元素。

Rivu, Rivu,

You are clearing temppath, but not removing it from mypath. 您正在清除temppath,但不是从mypath中删除它。 Hence, on second attempt you are referring to temppath again, which is blank. 因此,在第二次尝试时,您再次引用temppath,这是空白的。

if you want to remove temppath use 如果你想删除temppath使用

mypath.remove(temppath);

instead of 代替

temppath.clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM