为什么java.util.Arraylist#clear以OpenJDK的方式实现? [英] Why Was java.util.Arraylist#clear implemented the way it was in OpenJDK?

查看:135
本文介绍了为什么java.util.Arraylist#clear以OpenJDK的方式实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http:/ /grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#473

public void clear() {
    modCount++;

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

    size = 0;
}

我的问题是,为什么他们必须通过支持数组进行循环{O(n)}使每个元素有资格进行垃圾回收,只需重新初始化后备数组,放弃对整个数组的引用{O(1)}并使其符合垃圾回收的条件?
O(n)性能 clear()对我来说似乎不太好或者我错过了什么?

My question is, why did they have to do an cycle through the backing array { O(n) } to make each element eligible for garbage collection when they could just have reinitialized the backing array, discarding references to the entire array as a whole { O(1) } and making it eligible for garbage collection? O(n) performance for clear() doesn't seem so nice to me or am I missing something?

推荐答案

按照它们的方式执行操作可让您重用数组而无需重新分配其后备存储。如果你想重新分配数组,你可以自己完成,因为 ArrayList 的表示主要由它的后备存储组成。

Doing it the way they did lets you reuse the array without re-allocating its backing storage. If you wanted to reallocate the array, you could have done it yourself, since the representation of ArrayList mostly consists of its backing storage.

如果他们作为一个整体发布了数组,那么调用 clear()和重新分配 ArrayList之间几乎没有什么区别本身。现在,它们为您提供了重新选择阵列或将其替换为全新阵列的选项。

If they released the array as a whole, there would be very little difference between calling clear() and re-assigning the ArrayList itself. Now they give you an option to choose between reusing the array or replacing it with a brand-new one.

这篇关于为什么java.util.Arraylist#clear以OpenJDK的方式实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆