java 如何清除 ArrayList?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15991352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I clear an ArrayList?
提问by Jake
I have the following code in ThisClass
:
我有以下代码ThisClass
:
static ArrayList<MyClass> classlist;
If I call:
如果我打电话:
ThisClass.classlist = new ArrayList<MyClass>();
ThisClass.classlist.add(object);
And then call this line again:
然后再次调用此行:
ThisClass.classlist = new ArrayList<MyClass>();
Will it reset the ThisClass.classlist
list, i.e. the classlist list will no longer contain object?
它会重置ThisClass.classlist
列表,即类列表列表将不再包含对象吗?
回答by Jops
Here's an illustration:
这是一个插图:
Code 1: Creating the ArrayList and Adding an Object
代码 1:创建 ArrayList 并添加对象
ThisClass.classlist = new ArrayList<MyClass>();
ThisClass.classlist.add(object);
Results into this:
结果如下:
Code 2: Resetting through Re-initialization
代码 2:通过重新初始化重置
ThisClass.classlist = new ArrayList<MyClass>();
Results into this - you're resetting it by making it point to a fresh object:
结果 - 您通过使其指向一个新对象来重置它:
Code 3: Resetting by clearing the objects
代码 3:通过清除对象重置
What you should do to make it "no longer contain an object" is:
您应该做的是使其“不再包含对象”是:
ThisClass.classlist.clear();
Clear loops through all elements and makes them null. Well internally the ArrayList also points to the memory address of its objects, but for simplicity, just think that they're being "deleted" when you call this method.
Clear 循环遍历所有元素并使它们为null。在内部,ArrayList 也指向其对象的内存地址,但为简单起见,只需认为在调用此方法时它们正在被“删除”。
Code 4: Resetting the entire classlist
代码 4:重置整个类列表
If you want to make it "no longer contain an ArrayList" you do:
如果你想让它“不再包含一个 ArrayList”,你可以:
ThisClass.classlist = null;
Which means this:
这意味着:
Also, take note that your question's title mentions "static ArrayList". static
doesn't matter in this context. The result of your problem will be the same whether the object is static or not.
另外,请注意您的问题标题提到了“静态 ArrayList”。static
在这种情况下无关紧要。无论对象是否是静态的,您的问题的结果都是一样的。
回答by acdcjunior
Calling
打电话
ThisClass.classlist = new ArrayList<MyClass>();
does willclear the ThisClass.classlist
array (actually, will create a new ArrayList
and place it where the old one was).
do 将清除ThisClass.classlist
数组(实际上,将创建一个新数组ArrayList
并将其放在旧数组所在的位置)。
That being said, it is much better to use:
话虽如此,最好使用:
ThisClass.classlist.clear();
It is a way clearer approach: shows your true intention in the code, indicating what you are really trying to accomplish, thus making you code more readable/maintainable.
这是一种更清晰的方法:在代码中显示您的真实意图,表明您真正想要完成的工作,从而使您的代码更具可读性/可维护性。
回答by Jean Logeart
Correct.
正确的。
Technically, you do not clearthe ArrayList
doing so, you actually instantiate a new empty ArrayList
.
从技术上讲,你不清除的ArrayList
这样做,你实际上实例化一个新的空ArrayList
。