ArrayList 调整大小 [英] ArrayList resizing

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

问题描述

我有一个 ArrayList 对象,我知道它的确切大小.有什么办法可以指定ArrayList不应该扩展它的容量吗?

I have an ArrayList object for which I know the exact size. Is there any way to specify that the ArrayList should not extend its capacity?

List<String> list = null;
int size = getSize(); // gets the exact number of elements I want

list = new ArrayList<String> (size);

for (int i = 0; i < size; i++) {
    list.add("String num: " + i);
}

我不希望 ArrayList 重新调整大小,因为这需要我想避免浪费的时间.

I don't want the ArrayList to re-size because that takes time which I want to avoid wasting.

推荐答案

list = new ArrayList<String> (size);

这将创建以大小"作为初始容量的数组列表.只要您添加的元素不超过大小",就不会调整大小.

This will create arraylist with 'size' as initial capacity. As long as you don't add more elements than 'size' there will be no resizing.

另外请确保这在您的应用程序中确实需要时间.除非您已对此进行分析并将其确定为问题,否则您不会通过随机优化代码获得多少收益.

Also please be sure that this really takes time in your application. Unless you have profiled and identified this as issue, you will not gain much by randomly optimizing the code.

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

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