ArrayList.trimToSize()方法 [英] ArrayList.trimToSize() method

查看:104
本文介绍了ArrayList.trimToSize()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 ArrayList.trimToSize()动态ArrayList的方法是什么?

Can I use ArrayList.trimToSize() method in dynamic arrayList ?


  1. 如果我用它,有什么会发生?

  2. 我能使用动态的ArrayList这种方法带来任何好处。

  3. 在这种情况下,我应该用这种方法。

先谢谢了。

推荐答案

从文档您链接自己:

修剪此ArrayList实例的容量是列表的当前大小。应用程序可以使用此操作来最小化ArrayList实例的存储。

Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.

在内部的的ArrayList 存储保存所有项目的数组。在某些时刻的的ArrayList 将通过复制所有值到一个较大的阵列扩大这阵。发生这种情况时被添加的项目和要求的容量是比当前的大。会发生什么事在这一点上是code的以下行:

Internally an ArrayList stores an array that holds all the items. At certain moments the ArrayList will "expand" this array by copying all values into a larger array. This happens whenever an item is being added and the required capacity is bigger than the current one. What happens at this point is the following line of code:

int newCapacity = oldCapacity + (oldCapacity >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);

在本质上,这将创建一个新的数组,它是当前的大小的1.5倍。这是什么方法确实是调整内部数组,这样它没有留下空白空间。

In essence this will create a new array that is 1.5 times the size of the current one. What this method does is resize the internal array so that it has no empty space left.


  1. 什么都不会发生,对你可见。你不会丢失任何数据,它只是较小的支持数组。将数据添加到ArrayList将再次展开数组正常。

  1. Nothing will happen that's visible to you. You won't lose any data, it's just smaller backing array. Adding data to the arraylist will again expand the array normally.

我假设你的意思是一个正常的ArrayList 。如果你使用这个,你会减少使用的内存,但它也将是徒劳的,如果你仍然会后添加数据,这是pretty无用的小名单。如果你有很多很多的项目的的ArrayList ,你确定你不想再增加,那么你可以调用此方法,以减少一些内存占用。

I assume you mean a "normal" ArrayList. If you use this, you will reduce the memory used but it will also be futile if you will still add data after that AND it is pretty useless for small lists. If you have an ArrayList of many, many items and you're sure you don't want to add anymore then you can call this method to reduce some memory footprint.

见上面。我不认为它很可能你永远使用它。

See above. I don't think it's very likely you'll ever use this.

trimToSize()从源:

public void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (size < oldCapacity) {
        elementData = Arrays.copyOf(elementData, size);
    }
}

这篇关于ArrayList.trimToSize()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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