5

我正在查看 Java 文档,发现了 ArrayLists 的 clear() 方法。

与简单地将新的 ArrayList 对象重新分配给变量相比,这样做有什么用?

4

6 回答 6

14

因为可能对一个列表有多个引用,所以清除它可能比重新分配所有引用更可取和/或更实用。

如果您大量清空数组(例如,在一个大循环内),那么创建大量临时对象是没有意义的。当然,垃圾收集器最终会清理它们,但如果您不必这样做,那么浪费资源是没有意义的。

而且因为清除列表比创建新列表要少。

于 2009-05-05T22:45:15.413 回答
3

您可能有一个最终字段(类变量)List

private final List<Thing> things = ...

在课堂上的某个地方你想清除(删除所有)东西。由于things是最终的,因此无法重新分配。此外,您可能不想重新分配新的 List 实例,因为您已经实例化了一个完美的 List 。

于 2009-05-06T00:25:32.363 回答
2

java.util.ArrayList想象一下在整个代码中有多个相同引用的情况。创建列表的新实例并分配给所有变量几乎是不可能或非常困难的。但是java.util.ArrayList.clear()有诀窍!

于 2009-05-05T23:09:48.397 回答
2

如果您的目标是真正清除,则清除的费用比创建新对象的费用要少。

Reassigning a reference doesn't clear the object. The assumption is that if there are no other references to it, it would be reclaimed by the GC relatively soon. Otherwise, you just got yourself a mess.

于 2009-05-06T00:31:31.070 回答
2

In addition to the reasons mentioned, clearing a list is often more semantically correct than creating a new one. If your desired outcome is a cleared list, the action you should take is to clear the list, not create a new list.

于 2009-05-06T02:00:48.143 回答
1

clear() 不会重新分配新对象,因此对性能的影响较小。

于 2009-05-05T22:48:36.497 回答