栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java | ArrayList用法总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java | ArrayList用法总结

ArrayList是实现List接口的,底层采用数组实现。

ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。

基本方法  1、构造函数

     ArrayList提供了三个构造函数:

     ArrayList():默认构造函数,提供初始容量为10的空列表。

     ArrayList(int initialCapacity):构造一个具有指定初始容量的空列表。

     ArrayList(Collection c):构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。

2 、新增

      ArrayList提供了add(E e)、add(int index, E element)、addAll(Collection c)、addAll(int index, Collection c)、set(int index, E element)这个五个方法来实现ArrayList增加。

add(E e):将指定的元素添加到此列表的尾部。

add(int index, E element):将指定的元素插入此列表中的指定位置。

 addAll(Collection c):按照指定 collection 的迭代器所返回的元素顺序,将该 collection 中的所有元素添加到此列表的尾部。

addAll(int index, Collection c):从指定的位置开始,将指定 collection 中的所有元素插入到此列表中。

 set(int index, E element):用指定的元素替代此列表中指定位置上的元素。

3、删除

      ArrayList提供了remove(int index)、remove(Object o)、removeRange(int fromIndex, int toIndex)、removeAll()四个方法进行元素的删除。

remove(int index):移除此列表中指定位置上的元素。

remove(Object o):移除此列表中首次出现的指定元素(如果存在)。

removeRange(int fromIndex, int toIndex):移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。

removeAll():是继承自AbstractCollection的方法,ArrayList本身并没有提供实现。

2、遍历

(01) 第一种,通过迭代器遍历。即通过Iterator去遍历。

Integer value = null;
Iterator iter = list.iterator();
while (iter.hasNext()) {
    value = (Integer)iter.next();
}

(02) 第二种,随机访问,通过索引值去遍历。
由于ArrayList实现了RandomAccess接口,它支持通过索引值去随机访问元素。

Integer value = null;
int size = list.size();
for (int i=0; i 

(03) 第三种,for循环遍历。如下:

Integer value = null;
for (Integer integ:list) {
    value = integ;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/445165.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号