ArrayList的自动扩充机制实例解析
作者:ysk_xh_521 时间:2021-10-20 17:38:29
用一道选择题作为本文的开始吧!
ArrayList list = new ArrayList(20);中的list扩充几次
A.0
B.1
C.2
D.3
答案:A
1、ArrayList的默认初始容量为10,当然也可以自定义指定初始容量,随着动态的向其中添加元素,其容量可能会动态的增加,那么扩容的公式为:
新容量 = 旧容量/2 + 旧容量
比如:初始容量为4,其容量的每次扩充后的新容量为:4->6->9->13->19->…
即每次扩充至原有基础的1.5倍
ArrayList的构造函数总共有三个:
(1)ArrayList()构造一个初始容量为 10 的空列表。
(2)ArrayList(Collection<? extends E> c)构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
(3)ArrayList(int initialCapacity)构造一个具有指定初始容量的空列表。
调用的是第三个构造函数,直接初始化为大小为20的list,没有扩容,所以选择A
如果初始化为ArrayList(0),则会在新容量计算完毕后,增加至1;
另外与之类似的还有,
2、HashMap的初始大小为16,增长时,直接容量翻番,如源代码。
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);//原容量2倍
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
3、Vector的初始大小为10,如果没有指定每次增长的大小,则默认是翻倍增长。
来源:http://blog.csdn.net/ysk_xh_521/article/details/77529198
标签:java,arraylist,扩充
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java servlet、filter、listener、interceptor之间的区别和联系
2023-11-02 15:32:17
一文告诉你为什么要重写hashCode()方法和equals()方法
2021-09-05 07:05:55
SpringBoot中发送QQ邮件功能的实现代码
2022-09-25 10:19:59
![](https://img.aspxhome.com/file/2023/8/72648_0s.png)
java中LinkedBlockingQueue与ArrayBlockingQueue的异同
2023-08-19 02:56:49
![](https://img.aspxhome.com/file/2023/5/67185_0s.png)
Java的super关键字与instanceof运算符使用方法
2022-02-18 10:02:22
Java线程的调度与优先级详解
2023-04-30 13:48:13
细谈java同步之JMM(Java Memory Model)
2023-11-23 13:09:33
![](https://img.aspxhome.com/file/2023/3/59973_0s.png)
java代码实现MD5加密及验证过程详解
2023-09-26 02:50:45
使用Spring Data Redis实现数据缓存的方法
2021-08-02 10:19:25
![](https://img.aspxhome.com/file/2023/6/71706_0s.png)
Spring Boot 整合持久层之Spring Data JPA
2022-07-29 04:00:38
![](https://img.aspxhome.com/file/2023/9/62689_0s.png)
浅谈Java线程Thread之interrupt中断解析
2023-07-19 09:25:11
![](https://img.aspxhome.com/file/2023/4/57684_0s.png)
Java多线程的临界资源问题解决方案
2021-12-29 07:44:35
关于重写equals()方法和hashCode()方法及其简单的应用
2023-08-01 06:48:13
![](https://img.aspxhome.com/file/2023/5/57805_0s.jpg)
微信第三方登录Android实现代码
2023-07-27 08:05:49
![](https://img.aspxhome.com/file/2023/6/85986_0s.png)
Mybatis Limit实现分页功能
2022-03-14 13:57:57
![](https://img.aspxhome.com/file/2023/6/61646_0s.png)
在Flutter中制作翻转卡片动画的完整实例代码
2023-06-23 23:31:21
浅谈Java中Collections.sort对List排序的两种方法
2021-11-18 11:20:22
Mybatis常用分页插件实现快速分页处理技巧
2022-12-25 00:03:45
Mybatis Log Plugin的使用方式
2021-08-27 19:02:31
![](https://img.aspxhome.com/file/2023/8/61828_0s.jpg)
Spring创建bean实例的几种方式分享
2022-02-21 22:08:19