当前位置:网站首页>arraylist基操和添加元素源码
arraylist基操和添加元素源码
2022-06-29 02:31:00 【为什么不好好卖蛋饼】
ArrayList增加
List接口的实现类。
底层使用数组
查询效率高,增删效率低,不安全。
List<String> list=new ArrayList<>();
//添加元素
list.add("bjsxt");
list.add("puty");
//注意下面的添加方式数组索引不得大于现有元素个数
list.add(3,"jlhh");//此时报错
获取元素
for(int i=0;i<list.size(),i++){
sout(list.get(i));
}
删除元素
根据索引删除指定元素
返回值是被删除的元素的值
String value=list.remove(1);
替换元素
String val=list.set(0,"ibts");
清空容器
list.clear();
判断容器是否空
list.isEmpty();
是否包含指定元素
boolean flag=list.contains("xiaozhang");
到这里感觉特别无聊,直接跳过了一些东西。
ArrayList底层源码
AbstractList
private static final int DEFAULT_CAPACITY=10;
transienet Object[] elementData;
trasient 数据持久化 不会被保存磁盘
private int size;
public ArrayList(){
this.elementData=DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //{}
}
jdk1.7 立即加载
1.8 延迟加载 给空数组 什么时候用什么时候改变数组长度,合理使用空间。
add方法
核心是最后的grow方法,判断何时应该对数组做扩容。
public boolean add(E e){
ensureCapacityInternal(size+1);
elementData[size++]=e;
return true;
}
private void ensureCapacityInternal (int minCapacity){
ensureExplicitCapacity(calculateCapacity(elementData,minCapacity))
}
private static int calculateCapacity(Object[] elementData,int minCapacity){
if(elementData==DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
return Math.max(DEFAULT_CAPACITY,minCapacity);
}
return minCapacity;
}
private void ensureExpricitCapacity(int minCapacity){
modCount++;
if(minCapacity-elementData.length>0){
grow(minCapacity);
}
}
private void grow(int minCapacity){
int oldCapacity=elementData.length;
int newCapacity=oldCapacity+(oldCapacity>>1);
if(newCapacity-minCapacity<0){
newCapacity=minCapacity;
}
if(newCapacity-MAX_ARRAY_SIZE>0){
newCapacity=hugeCapacity(minCapacity);
}
elementData=Arrays.copyOf(elementData,newCapacity);
}
边栏推荐
- Use code binding DataGridView control to display tables in program interface
- Troubleshooting of pyinstaller failed to pack pikepdf
- EMC、EMI、EMS的关系
- China's flexible employment has reached 200million
- MySQL的下载和安装
- 字符串替换
- QT basics tutorial: data types and containers
- Use photoshop2022 to create a wonderful gradient effect for pictures
- [redis] data introduction & General Command & string type
- 哪个证券公司最大最安全 哪家券商服务好
猜你喜欢
随机推荐
Handling method of occasional error reporting on overseas equipment
信息学奥赛一本通 1361:产生数(Produce) | 洛谷 P1037 [NOIP2002 普及组] 产生数
Koa 快速入门
“内窥镜第一股”二闯IPO,去年亏损5个亿,核心产品商业化仍存疑 | IPO速递
Studies of relative costs for development in different languages
Boost the digital economy and face the future office | the launch of the new version of spreadjsv15.0 is about to begin
Introduction to openresty
三角函数计算
mgalcu-a509
PHP XML expat parser
Why should the pointer be null after delete
Use code binding DataGridView control to display tables in program interface
String output
SystemVerilog structure (I)
Junior final exam
Chrome browser close update Popup
字符串输出
Cross border information station
【学习笔记】子集和问题
安装kibana




![[redis] list type](/img/c7/adec2aaea50d69a0aed95bfe683b9e.png)



