Java 中的 clear() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1717570/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:50:49  来源:igfitidea点击:

clear() methods in Java

javacollections

提问by flyingfromchina

Many of the container type data structures in Java come with a clear()method. For example, we can call clear()on a Vectorwe want to clear out all the contents in the Vector. My question is after applying the clear()method, does the content in the vector get nulled out or are they still being referenced? Thanks.

Java 中的许多容器类型数据结构都带有clear()方法。例如,我们可以调用clear()一个Vector我们想要清除Vector. 我的问题是在应用该clear()方法后,向量中的内容是否被清空了,还是仍然被引用?谢谢。

采纳答案by MarkPowell

They are no longer referenced by the Collection, but if you have any references anywhere in your code, that reference continues to exist as it was.

它们不再被 Collection 引用,但如果您在代码中的任何地方有任何引用,该引用将继续按原样存在。

As mentioned, Vector's source does call:

如前所述,Vector 的源代码确实调用了:

// Let gc do its work
for (int i = 0; i < elementCount; i++)
    elementData[i] = null;

However, this is setting it's internal reference to null (pass-by-value) and will not affect any external references.

但是,这是将其内部引用设置为 null(按值传递)并且不会影响任何外部引用。

回答by Fabian Steeg

If not referenced from elsewhere, they will be garbage collected.

如果没有从其他地方引用,它们将被垃圾收集。

回答by Bozho

//Let gc do its work
for (int i = 0; i < elementCount; i++) 
    elementData[i] = null;

This is the code, with the comment from the Vector class. It answers the question, I think.

这是代码,带有来自 Vector 类的注释。它回答了这个问题,我想。

回答by BalusC

They don't get nulled out --this makes no sense, it's only the reference which becomes null, not the value--, they simply get dereferenced. If they don't have any other reference on it (e.g. another class having it referenced as a static or instance variable), then they will be eligible for GC.

它们不会被清除——这没有意义,只是引用变为空,而不是值——,它们只是被取消引用。如果他们没有任何其他引用(例如另一个类将它作为静态或实例变量引用),那么他们将有资格进行 GC。

回答by matt b

When it doubt, you can just take a look at the source code - it is bundled with the JDK (usually in a file named rt.zip).

如果有疑问,您可以查看源代码 - 它与 JDK 捆绑在一起(通常在一个名为 的文件中rt.zip)。

public void clear() {
    removeAllElements();
}

public synchronized void removeAllElements() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}

The "Let gc do its work" comment is from the actual source, not mine.

“让 gc 做它的工作”评论来自实际来源,而不是我的。

回答by DZaki

while(!stack.isEmpty()){
    System.out.println(stack.pop());
    System.out.println(stack);
}