ArrayList的容量 [英] Capacity of ArrayList

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

问题描述

可能的重复:
Java中如何获取ArrayList的容量?

如何求ArrayList的容量?

推荐答案

我很好奇,你需要它做什么?您应该知道容量并不是(听起来可能)您可以放入 ArrayList 的上限.它是一个值,表示您可以将多少数据放入列表中,而不强制它重新分配内部数组.基本上,容量的概念只是为了让您稍微调整性能.

I'm curious, what do you need it for? You should know that the capacity is not (as it may sound) an upper limit of how much you can put into the ArrayList. It's a value representing how much data you can put into the list, without forcing it to reallocate it internal array. Basically, the notion of capacity is only there in order for you to tweak the performance slightly.

无论如何,也许你已经知道了,所以这里是真正的答案.

Anyway, perhaps you already know that, so here comes the actual answer.

API 为 ArrayList 提供的接口只是不支持这种用例.这件事情是由很多原因导致的.一个原因是你不应该关心这个.ArrayList 被认为是一个无界数组,它从容量等细节中抽象出来.

The interface provided by API for ArrayList simply doesn't support such use case. There are many reasons for this. One reason is that you shouldn't care about this. The ArrayList is to be thought of as an unbounded array which abstracts away from details such as capacity.

最接近控制容量的是通过构造函数 ArrayList(int initialCapacity),以及两种方法trimToSize()ensureCapacity(int minCapacity).

The closest you can get to controlling the capacity is through the constructor ArrayList(int initialCapacity), and the two methods trimToSize() and ensureCapacity(int minCapacity).

不过,为了好玩,我设法通过一个丑陋的反射黑客来解决它(不要使用这个):

For fun however, I managed to solve it through an ugly reflection-hack (don't use this):

import java.lang.reflect.Field;
import java.util.ArrayList;
public class Test {

    public static void main(String[] args) throws Exception {
        ArrayList<Integer> list = new ArrayList<Integer>(3);
        for (int i = 0; i < 17; i++) {
            list.add(i);
            System.out.format("Size: %2d, Capacity: %2d%n",
                              list.size(), getCapacity(list));
        }
    }

    static int getCapacity(ArrayList<?> l) throws Exception {
        Field dataField = ArrayList.class.getDeclaredField("elementData");
        dataField.setAccessible(true);
        return ((Object[]) dataField.get(l)).length;
    }
}

输出:

Size:  1, Capacity:  3
Size:  2, Capacity:  3
Size:  3, Capacity:  3
Size:  4, Capacity:  5
Size:  5, Capacity:  5
Size:  6, Capacity:  8
Size:  7, Capacity:  8
Size:  8, Capacity:  8
Size:  9, Capacity: 13
Size: 10, Capacity: 13
Size: 11, Capacity: 13
Size: 12, Capacity: 13
Size: 13, Capacity: 13
Size: 14, Capacity: 20
Size: 15, Capacity: 20
Size: 16, Capacity: 20
Size: 17, Capacity: 20

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

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