集合.Collection体系集合

Collection父接口

特点:代表一组任意类型的对象,无序,无下标,不能重复

方法:

  • boolean add(Object obj);添加一个对象

  • boolean addAll(Collection c);将一个集合中的所有对象添加到此集合中

  • void clear();清空此集合中的所有对象

  • boolean contains(Object o);检查此集合中是否包含o对象

  • boolean equals(Object o);比较此集合是否与指定对象相等

  • boolean isEmpty();判断此集合是否为空

  • boolean remove(Object o);在此集合中移除o对象

  • int size();返回此集合中的元素个数

  • Object[] toArray();将此集合转换成数组

复制代码
package jihe;

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

/**
 * Collection接口的使用
 * 1.添加元素
 * 2.删除元素
 * 3.遍历元素
 * 4.判断
 */
public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        Collection collection = new ArrayList();
        //1.添加元素
        collection.add("苹果");
        collection.add("西瓜");
        collection.add("榴莲");
        System.out.println("元素个数"+collection.size());
        System.out.println(collection);
        
        //2.删除元素
        //collection.remove("苹果");
        //collection.clear();//清空
        //System.out.println("删除之后"+collection.size());
        //System.out.println(collection);
        
        //3.遍历元素(重点)
        //3.1使用增强for  collection.for+Tab键
        System.out.println("-------使用增强for--------");
        for (Object object : collection) {
            System.out.println(object);
        }
        //3.2使用迭代器(专门用来遍历集合的一种方式)
        //hasNext();有没有下一个元素
        //next();获取下一个元素
        //remove();删除当前元素
        System.out.println("-------使用迭代器--------");
        Iterator it = collection.iterator();
        while (it.hasNext()){
            String s =(String)it.next();
            System.out.println(s);
            //collection.remove(s);在迭代过程中不能使用collection.remove();方法删除
            //it.remove();
        }
        System.out.println("元素个数"+collection.size());

        //4.判断
        System.out.println(collection.contains("西瓜"));
        System.out.println(collection.contains("橘子"));
        System.out.println(collection.isEmpty());//判断是否为空,空为true,不空为false
    }
}
复制代码

 

posted @   sususyq-  阅读(20)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示