List接口常用方法的测试
List接口中存储数据的特点
用于存储有序的、可以重复的数据。
List中的常用方法
Collection
中声明的十五个方法
List及其实现类特点
(1)add(E obj):添加元素对象到当前集合中
(2) addAll(Collection other):添加other集合中的所有元素对象到当前集合中,即this = this ∪ other
(3)int size():获取当前集合中实际存储的元素个数
(4)boolean isEmpty():判断当前集合是否为空集合
(5)boolean contains(Object obj):判断当前集合中是否存在一个与obj对象equals返回true的元素
(6)boolean containsAll(Collection coll):判断coll集合中的元素是否在当前集合中都存在。即coll集合是否是当前集合的“子集”
(7)boolean equals(Object obj):判断当前集合与obj是否相等
(8)void clear():清空集合元素
(9) boolean remove(Object obj) :从当前集合中删除第一个找到的与obj对象equals返回true的元素。 (考虑结果时,应考虑是否 equals方法)
(10)boolean removeAll(Collection coll):从当前集合中删除所有与coll集合中相同的元素。即this = this - this ∩ coll
(11)boolean retainAll(Collection coll):从当前集合中删除两个集合中不同的元素,使得当前集合仅保留与coll集合中的元素相同的元素,即当前集合中仅保留两个集合的交集,即this = this ∩ coll;
(12)Object[] toArray():返回包含当前集合中所有元素的数组
(13)hashCode():获取集合对象的哈希值
(14)iterator():返回迭代器对象,用于集合遍历
因为List是有序的,则在List也增添了些针对索引的方法
插入元素
void add(int index, Object ele)
:在index位置插入ele元素boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
获取元素
Object get(int index)
:获取指定index位置的元素List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
获取元素索引
int indexOf(Object obj):返回obj在集合中首次出现的位置
int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
删除和替换元素
Object remove(int index)
:移除指定index位置的元素,并返回此元素
Object set(int index, Object ele)
:设置指定index位置的元素为ele
使用remove()
的细节
-
remove(Object obj)
public class Test{ public static void main(String []args){ List list = new ArrayList(); list.add("AA"); list.add("BB"); list.add(2); list.add(3); System.out.println(list.toString()); list.remove(Integer.valueOf(2)); System.out.println(list.toString()); } } [AA, BB, CC, 2, 3] [AA, BB, CC, 3] 删除值为2的数据
-
remove(int index)
public class Test{ public static void main(String []args){ List list = new ArrayList(); list.add("AA"); list.add("BB"); list.add(2); list.add(3); System.out.println(list.toString()); list.remove(2); System.out.println(list.toString()); } } //此时,直接使用2,则会删除index为2的数据 //[AA, BB, CC, 2, 3] //[AA, BB, 2, 3]