当前位置: 首页 > article >正文

【Java】—— 集合框架:Collection接口中的方法与迭代器(Iterator)

目录

1. 集合框架概述

1.1 生活中的容器

1.2 数组的特点与弊端

1.3 Java集合框架体系

1.4 集合的使用场景

2. Collection接口及方法

2.1 添加

2.2 判断

2.3 删除

2.4 其它

3. Iterator(迭代器)接口

3.1 Iterator接口

3.2 迭代器的执行原理

3.3 foreach循环


1. 集合框架概述

1.1 生活中的容器

1.2 数组的特点与弊端

  • 一方面,面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象的操作,就要对对象进行存储。

  • 另一方面,使用数组存储对象方面具有一些弊端,而Java 集合就像一种容器,可以动态地把多个对象的引用放入容器中。

  • 数组在内存存储方面的特点

    • 数组初始化以后,长度就确定了

    • 数组中的添加的元素是依次紧密排列的有序的,可以重复的。

    • 数组声明的类型,就决定了进行元素初始化时的类型。不是此类型的变量,就不能添加。

    • 可以存储基本数据类型值,也可以存储引用数据类型的变量

  • 数组在存储数据方面的弊端

    • 数组初始化以后,长度就不可变了,不便于扩展

    • 数组中提供的属性和方法少不便于进行添加、删除、插入、获取元素个数等操作,且效率不高。

    • 数组存储数据的特点单一,只能存储有序的、可以重复的数据

  • Java 集合框架中的类可以用于存储多个对象,还可用于保存具有映射关系的关联数组。

1.3 Java集合框架体系

Java 集合可分为 Collection 和 Map 两大体系:

  • Collection接口:用于存储一个一个的数据,也称单列数据集合

    • List子接口:用来存储有序的可以重复的数据(主要用来替换数组,"动态"数组)

      • 实现类:ArrayList(主要实现类)、LinkedList、Vector

    • Set子接口:用来存储无序的不可重复的数据(类似于高中讲的"集合")

      • 实现类:HashSet(主要实现类)、LinkedHashSet、TreeSet

  • Map接口:用于存储具有映射关系“key-value对”的集合,即一对一对的数据,也称双列数据集合。(类似于高中的函数、映射。(x1,y1),(x2,y2) ---> y = f(x) )

    • HashMap(主要实现类)、LinkedHashMap、TreeMap、Hashtable、Properties

  • JDK提供的集合API位于java.util包内

  • 图示:集合框架全图

  • 简图1:Collection接口继承树

  • 简图2:Map接口继承树

1.4 集合的使用场景

2. Collection接口及方法

  • JDK不提供此接口的任何直接实现,而是提供更具体的子接口(如:Set和List)去实现。

  • Collection 接口是 List和Set接口的父接口,该接口里定义的方法既可用于操作 Set 集合,也可用于操作 List 集合。方法如下:

2.1 添加

(1)add(E obj):添加元素对象到当前集合中
(2)addAll(Collection other):添加other集合中的所有元素对象到当前集合中,即this = this ∪ other

注意:add和addAll的区别

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;

public class TestCollectionAdd {
    @Test
    public void testAdd(){
        //ArrayList是Collection的子接口List的实现类之一。
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
        System.out.println(coll);
    }

    @Test
    public void testAddAll(){
        Collection c1 = new ArrayList();
        c1.add(1);
        c1.add(2);
        System.out.println("c1集合元素的个数:" + c1.size());//2
        System.out.println("c1 = " + c1);

        Collection c2 = new ArrayList();
        c2.add(1);
        c2.add(2);
        System.out.println("c2集合元素的个数:" + c2.size());//2
        System.out.println("c2 = " + c2);

        Collection other = new ArrayList();
        other.add(1);
        other.add(2);
        other.add(3);
        System.out.println("other集合元素的个数:" + other.size());//3
        System.out.println("other = " + other);
        System.out.println();

        c1.addAll(other);
        System.out.println("c1集合元素的个数:" + c1.size());//5
        System.out.println("c1.addAll(other) = " + c1);

        c2.add(other);
        System.out.println("c2集合元素的个数:" + c2.size());//3
        System.out.println("c2.add(other) = " + c2);
    }
}

注意:coll.addAll(other);与coll.add(other);

2.2 判断

(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是否相等

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class TestCollectionContains {
    @Test
    public void test01() {
        Collection coll = new ArrayList();
        System.out.println("coll在添加元素之前,isEmpty = " + coll.isEmpty());
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
        coll.add("佛地魔");
        System.out.println("coll的元素个数" + coll.size());

        System.out.println("coll在添加元素之后,isEmpty = " + coll.isEmpty());
    }

    @Test
    public void test02() {
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
        coll.add("佛地魔");
        System.out.println("coll = " + coll);
        System.out.println("coll是否包含“小李广” = " + coll.contains("小李广"));
        System.out.println("coll是否包含“宋红康” = " + coll.contains("宋红康"));

        Collection other = new ArrayList();
        other.add("小李广");
        other.add("扫地僧");
        other.add("尚硅谷");
        System.out.println("other = " + other);

        System.out.println("coll.containsAll(other) = " + coll.containsAll(other));
    }

    @Test
    public void test03(){
        Collection c1 = new ArrayList();
        c1.add(1);
        c1.add(2);
        System.out.println("c1集合元素的个数:" + c1.size());//2
        System.out.println("c1 = " + c1);

        Collection c2 = new ArrayList();
        c2.add(1);
        c2.add(2);
        System.out.println("c2集合元素的个数:" + c2.size());//2
        System.out.println("c2 = " + c2);

        Collection other = new ArrayList();
        other.add(1);
        other.add(2);
        other.add(3);
        System.out.println("other集合元素的个数:" + other.size());//3
        System.out.println("other = " + other);
        System.out.println();

        c1.addAll(other);
        System.out.println("c1集合元素的个数:" + c1.size());//5
        System.out.println("c1.addAll(other) = " + c1);
        System.out.println("c1.contains(other) = " + c1.contains(other));
        System.out.println("c1.containsAll(other) = " + c1.containsAll(other));
        System.out.println();

        c2.add(other);
        System.out.println("c2集合元素的个数:" + c2.size());
        System.out.println("c2.add(other) = " + c2);
        System.out.println("c2.contains(other) = " + c2.contains(other));
        System.out.println("c2.containsAll(other) = " + c2.containsAll(other));
    }

}

2.3 删除

(8)void clear():清空集合元素
(9) boolean remove(Object obj) :从当前集合中删除第一个找到的与obj对象equals返回true的元素。
(10)boolean removeAll(Collection coll):从当前集合中删除所有与coll集合中相同的元素。即this = this - this ∩ coll
(11)boolean retainAll(Collection coll):从当前集合中删除两个集合中不同的元素,使得当前集合仅保留与coll集合中的元素相同的元素,即当前集合中仅保留两个集合的交集,即this = this ∩ coll

注意几种删除方法的区别

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Predicate;

public class TestCollectionRemove {
    @Test
    public void test01(){
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
        coll.add("佛地魔");
        System.out.println("coll = " + coll);

        coll.remove("小李广");
        System.out.println("删除元素\"小李广\"之后coll = " + coll);
        
        coll.clear();
        System.out.println("coll清空之后,coll = " + coll);
    }

    @Test
    public void test02() {
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
        coll.add("佛地魔");
        System.out.println("coll = " + coll);

        Collection other = new ArrayList();
        other.add("小李广");
        other.add("扫地僧");
        other.add("尚硅谷");
        System.out.println("other = " + other);

        coll.removeAll(other);
        System.out.println("coll.removeAll(other)之后,coll = " + coll);
        System.out.println("coll.removeAll(other)之后,other = " + other);
    }

    @Test
    public void test03() {
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
        coll.add("佛地魔");
        System.out.println("coll = " + coll);

        Collection other = new ArrayList();
        other.add("小李广");
        other.add("扫地僧");
        other.add("尚硅谷");
        System.out.println("other = " + other);

        coll.retainAll(other);
        System.out.println("coll.retainAll(other)之后,coll = " + coll);
        System.out.println("coll.retainAll(other)之后,other = " + other);
    }

}

2.4 其它

(12)Object[] toArray():返回包含当前集合中所有元素的数组
(13)hashCode():获取集合对象的哈希值
(14)iterator():返回迭代器对象,用于集合遍历

3. Iterator(迭代器)接口

3.1 Iterator接口

  • 在程序开发中,经常需要遍历集合中的所有元素。针对这种需求,JDK专门提供了一个接口java.util.IteratorIterator接口也是Java集合中的一员,但它与CollectionMap接口有所不同。

    • Collection接口与Map接口主要用于存储元素

    • Iterator,被称为迭代器接口,本身并不提供存储对象的能力,主要用于遍历Collection中的元素

  • Collection接口继承了java.lang.Iterable接口,该接口有一个iterator()方法,那么所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象。

    • public Iterator iterator(): 获取集合对应的迭代器,用来遍历集合中的元素的。

    • 集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。

  • Iterator接口的常用方法如下:

    • public E next():返回迭代的下一个元素。

    • public boolean hasNext():如果仍有元素可以迭代,则返回 true

  • 注意:在调用it.next()方法之前必须要调用it.hasNext()进行检测。若不调用,且下一条记录无效,直接调用it.next()会抛出NoSuchElementException异常

举例:

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class TestIterator {
    @Test
    public void test01(){
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");

        Iterator iterator = coll.iterator();
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next()); //报NoSuchElementException异常
    }

    @Test
    public void test02(){
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");

        Iterator iterator = coll.iterator();//获取迭代器对象
        while(iterator.hasNext()) {//判断是否还有元素可迭代
            System.out.println(iterator.next());//取出下一个元素
        }
    }
}

3.2 迭代器的执行原理

        Iterator迭代器对象在遍历集合时,内部采用指针的方式来跟踪集合中的元素,接下来通过一个图例来演示Iterator对象迭代元素的过程:

使用Iterator迭代器删除元素:java.util.Iterator迭代器中有一个方法:void remove() ;

注意:

  • Iterator可以删除集合的元素,但是遍历过程中通过迭代器对象的remove方法,不是集合对象的remove方法。

  • 如果还未调用next()或在上一次调用 next() 方法之后已经调用了 remove() 方法,再调用remove()都会报IllegalStateException。

  • Collection已经有remove(xx)方法了,为什么Iterator迭代器还要提供删除方法呢?因为迭代器的remove()可以按指定的条件进行删除。

3.3 foreach循环

  • foreach循环(也称增强for循环)是 JDK5.0 中定义的一个高级for循环,专门用来遍历数组和集合的。

  • foreach循环的语法格式:

for(元素的数据类型 局部变量 : Collection集合或数组){ 
    //操作局部变量的输出操作
}
//这里局部变量就是一个临时变量,自己命名就可以
  • 举例:

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;

public class TestForeach {
    @Test
    public void test01(){
        Collection coll = new ArrayList();
        coll.add("小李广");
        coll.add("扫地僧");
        coll.add("石破天");
		//foreach循环其实就是使用Iterator迭代器来完成元素的遍历的。
        for (Object o : coll) {
            System.out.println(o);
        }
    }
    @Test
    public void test02(){
        int[] nums = {1,2,3,4,5};
        for (int num : nums) {
            System.out.println(num);
        }
        System.out.println("-----------------");
        String[] names = {"张三","李四","王五"};
        for (String name : names) {
            System.out.println(name);
        }
    }
}
  • 对于集合的遍历,增强for的内部原理其实是个Iterator迭代器。如下图。

  • 它用于遍历Collection和数组。通常只进行遍历元素,不要在遍历的过程中对集合元素进行增删操作


http://www.kler.cn/news/329886.html

相关文章:

  • 基于Springboot的在线订餐系统设计与实现(论文+源码)_kaic
  • STM32使用Keil5 在运行过程中不复位进入调试模式
  • Html5知识点介绍
  • SpringCloud-基于Docker和Docker-Compose的项目部署
  • python UNIT3 选择与循环(1)
  • 使用微服务Spring Cloud集成Kafka实现异步通信
  • 【Java基础】Java面试基础知识QA(上)
  • 关于主流电商API接口的测试及返回【douyin电商SKU接口】
  • 螺狮壳里做道场:老破机搭建的私人数据中心---Centos下Docker学习01(环境准备)
  • 基于深度学习的图像去噪与去模糊
  • ACL(Access Control List)访问控制列表
  • 彩虹易支付最新版源码及安装教程(修复BUG+新增加订单投诉功能)
  • 推送k8s镜像到阿里云服务器
  • 滚雪球学Oracle[2.5讲]:数据库初始化配置
  • 开发指南063-上传文件到百度网盘
  • MindSearch 部署到Github Codespace 和 Hugging Face Space
  • VUE3.5版本解读
  • 5G NR 协议规范表(对应3GPP 协议编号)
  • django的模型层介绍与配置
  • 【历年CSP-S复赛第一题】暴力解法与正解合集(2019-2022)
  • 文心一言智能体——绿色生活管家
  • 如何通过python+sqlalchemy获得MSsql视图的结构
  • 【HarmonyOS】时间处理Dayjs
  • ASP.NET Zero是什么?适合哪些业务场景?
  • 21.2 k8s中etcd的tls双向认证原理解析
  • 【有啥问啥】规划与控制算法详解:从原理到应用及未来展望
  • NeRF2: Neural Radio-Frequency Radiance Fields 笔记
  • redis快速上手
  • docker export/import 和 docker save/load 的区别
  • Unity3D播放GIF图片使用Animation来制作动画