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

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

问题描述

我可以使用 ArrayList.trimToSize() 动态 arrayList 中的方法?

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

  1. 如果我使用它,会发生什么?
  2. 在动态 ArrayList 上使用此方法是否可以获得任何好处.
  3. 在这种情况下,我应该使用这种方法.

提前致谢.

推荐答案

来自您链接自己的文档:

From the docs you link yourself:

将此 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 会通过将所有值复制到更大的数组中来扩展"这个数组.每当添加项目并且所需容量大于当前容量时,就会发生这种情况.此时发生的是以下代码行:

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.如果您使用它,您将减少使用的内存,但如果您在此之后仍然添加数据,它也将是徒劳的,并且对于小列表来说非常无用.如果您有一个包含许多项的 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天全站免登陆