Java | ArrayList用法总结

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

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

基本方法

 1、构造函数

     ArrayList提供了三个构造函数:

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

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

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

2 、新增

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

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

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

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

addAll(int index, Collection<? extends E> 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<size; i++) {
    value = (Integer)list.get(i);        
}

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

Integer value = null;
for (Integer integ:list) {
    value = integ;
}

猜你喜欢

转载自blog.csdn.net/weixin_48419914/article/details/121191944
今日推荐