ArrayList的大小调整 [英] ArrayList resizing

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

问题描述

我有一个ArrayList对象,我知道确切的大小。有什么方法来指定的ArrayList不应扩大它的能力?

 列表<串GT;名单= NULL;
INT大小=的getSize(); //获取元素的确切数目我想名单=新的ArrayList<串GT; (尺寸);的for(int i = 0; I<大小;我++){
    list.add(新的String(字符串编号:+ I);
}

我不希望因为ArrayList中需要时间,我想,以避免浪费重新大小。


解决方案

 列表=新的ArrayList<串GT; (尺寸);

这将创建一个与大小为初始容量的ArrayList。只要不超过大小加入更多的元素不会有调整大小。

此外,请务必,这确实需要时间在你的应用程序。除非你有异形,并确定这是问题,你会不会通过随机优化code增益了。

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(new String("String num: " + i);
}

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天全站免登陆