java arraylist iterator_java中arraylist的用法

Java (1) 2024-06-14 10:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
java arraylist iterator_java中arraylist的用法,希望能够帮助你!!!。

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

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

java arraylist iterator_java中arraylist的用法_https://bianchenghao6.com/blog_Java_第1张

java arraylist iterator_java中arraylist的用法_https://bianchenghao6.com/blog_Java_第2张

基本方法

 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; }

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

下一篇

已是最新文章

发表回复