2023-11-23

发布时间 2023-11-24 16:26:07作者: 神烦狗~

2023-11-23

集合体系结构

捕获

1

Collection接口和常用方法

常用方法

  1. add() 添加单个元素
  2. remove() 删除指定元素
  3. contains() 查找元素是否存在
  4. size() 获取元素个数
  5. isEmpty() 判断是否为空
  6. clear() 清空
  7. addAll() 添加多个元素
  8. containsAll() 查找多个元素是否存在
  9. removAll() 删除多个元素。

Collection接口遍历元素方式

1.使用Iterator(迭代器)

        List arrayList = new ArrayList<>();//创建一个集合arrayList

        Iterator iterator = arrayList.iterator();//得到arrayList集合的迭代器

        while(iterator.hasNext()){//判断是否有下一个元素
            System.out.println(iterator.next());//如果有则(1)下移(2)将下移后的元素返回
        }

        //如果希望再次遍历 需要重置迭代器
        iterator = arrayList.iterator; 

2.增强for循环(底层仍然是迭代器)

for(元素类型 元素名 : 集合名或数组名){
	访问元素
}

List接口和常用方法

基本了解

  1. List集合中元素有序且可重复
  2. List中所有元素都有其对应的顺序索引,即支持索引
  3. List中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素

常用方法

add(int index , Object eles) 在index位置插入eles元素

addAll(int index , collection eles) 从index位置将eles所有元素插入

get(int index) 获取index位置上的元素

indexOf(Objec obj) 返回obj在集合中首次出现的位置

lastIndexOf(Objec obj) 返回obj在集合中最后出现的位置

remove(int index) 移除index位置上的元素,并返回该元素

set(int index , collection eles) 将指定位置index上的元素改为eles

subList(int fromIndex ,int toIndex ) 返回formIndex<=到<toIndex位置的子集合

List接口遍历元素方式

  1. 迭代器
  2. 增强for
  3. 普通for