Java的ArrayList的清算:如何清除()的作品 [英] Java Arraylist clearing : how clear() works
问题描述
我有对象mypath中的二维列表列表<名单,LT;对象>> mypath中=新的ArrayList<名单,LT;对象>>();
。假设我有code的以下行
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));
我看到第一个print语句对象的列表,但是从第二打印一个空列表。当我明确TEMPPATH,mypath中的这个元素也将被清除时出现。有没有办法来规避这个问题?我可以明确TEMPPATH,不清除mypath中的最后一个元素?
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?
推荐答案
由于两者都指的是同一个对象
堆,使它像
because both are referring to same Object
in heap, make it like
mypath.add(new ArrayList<Object>(temppath));
这将创建 TEMPPATH
<子>如果它不会伤害到你的应用程序
这篇关于Java的ArrayList的清算:如何清除()的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!