当前位置 博文首页 > AiY..的博客:Collection接口

    AiY..的博客:Collection接口

    作者:[db:作者] 时间:2021-07-14 21:32

    集合:对象的容器,定义了多个对象操作的常用方法,实现数组的功能;长度不固定;位于java.uitl.*包;
    一:
    1、Collection接口:

    (1)List 有序集合,允许相同元素和null,有下标
    LinkedList 非同步,允许相同元素和null,遍历效率低插入和删除效率高
    ArrayList 非同步,允许相同元素和null,实现了动态大小的数组,遍历效率高,用的多
    Vector 同步,允许相同元素和null,效率低
    Stack 继承自Vetor,实现一个后进先出的堆栈
    (2)Set 无序集合,不允许相同元素,最多有一个null元素,无下标
    HashSet 无序集合,不允许相同元素,最多有一个null元素
    TreeSet 有序集合,不允许相同元素,最多有一个null元素
    在这里插入图片描述

    2、Collection接口的功能:
    (1)单个元素的的添加和删除

    public boolean add(Object obj)//向collection中添加指定元素
    public boolean remove(Object obj) //删除collection中的指定元素
    

    (2)组元素的添加、删除

    public boolean addAll(Collection col) //向collection中添加指定的一组对象
    public boolean removeAll(Collection col)//删除collection中指定的一组对象//删除两个集合的交集
    public boolean retainAll(Collection col)//删除仅在collection中而不在col中的对象//保留两个集合的交集,其他删除
    public boolean clear()//清空collection中对象的个数
    

    (3)查询

    public boolean contains(Object obj) //查询collection中是否含指定的对象obj
    public boolean isEmpty() //查询collection中是否存在对象
    public int size()  //获取collection中对象的个数
    

    Collection接口的代码:

    package Fanxing;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    
    /***
     * Collection接口
     * (1)添加元素
     * (2)删除元素
     * (3)遍历元素
     * (4)清空
     * @author AiY
     */
    public class Demo1 {
        public static void main(String[] args) {
            //创建集合
            Collection collection=new ArrayList();
            //添加元素
            collection.add("苹果");
            collection.add("香蕉");
            collection.add("橘子");
            System.out.println("元素个数:"+collection.size());
            System.out.println(collection);
            //删除对象
            System.out.println("------删除元素后遍历--------");
            collection.remove("香蕉");
            System.out.println("删除之后元素为:"+collection);
            //遍历元素
            collection.add("西瓜");
            System.out.println("-----增强for遍历-----------");
                //增强for遍历,不显示下标
            for(Object object : collection){
                System.out.println(object);
            }
            System.out.println("-----迭代器遍历-------------");
                //使用迭代器遍历(主要遍历集合的一种方式)//hasNext()-有没有下一个元素;
                //next()-获取下一个元素//remove()-删除当前元素
            Iterator it =collection.iterator();
            while(it.hasNext()){
                String element=(String)it.next();//强制转换//element元素的意思
                System.out.println(element);
            }
            //清空
            System.out.println("-----清空后遍历-------");
            collection.clear();
            System.out.println("清空之后元素:"+collection);
        }
    }
    
    

    运行结果:

    元素个数:3
    [苹果, 香蕉, 橘子]
    ------删除元素后遍历--------
    删除之后元素为:[苹果, 橘子]
    -----增强for遍历-----------
    苹果
    橘子
    西瓜
    -----迭代器遍历-------------
    苹果
    橘子
    西瓜
    -----清空后遍历-------
    清空之后元素:[]
    
    cs
    下一篇:没有了