集合(1)Collection接口的使用
集合的概念:对象的容器,定义了对多个对象进行操作的常用方法,可实现数组的功能。
和数组的区别:①数组长度固定,集合长度不固定
②数组可以存储基本类型和引用类型,而集合只能存储引用类型。
Collection体系:
Collection接口的使用:①添加元素--add();②删除元素--remove();③遍历元素--可用增强的for循环,也可使用迭代器Iterator。
/** * Collection接口的使用 * 1.添加元素 * 2.删除元素 * 3.遍历元素 * 4.判断 * @author 长空扯淡 */ public class Demo01 { public static void main(String[] args) { //创建集合 Collection collection = new ArrayList(); // * 1.添加元素 collection.add("西瓜"); collection.add("香蕉"); collection.add("火龙果"); System.out.println(collection);//输出--[西瓜, 香蕉, 火龙果] System.out.println("==========================="); // * 2.删除元素 collection.remove("香蕉"); //collection.clear();//清除 System.out.println("删除之后:"+collection.size());//输出--删除结果:2 System.out.println("==========================="); // * 3.遍历元素【重点】 //3.1用增强的for循环 for(Object obj:collection){ System.out.println(obj);//输出--西瓜 } 火龙果 System.out.println("==========================="); //3.2使用迭代器(专门用来遍历集合的一种方式) /* hasNext();有没有下一个元素 next();获取下一个元素 remove();删除当前元素 */ Iterator it = collection.iterator(); while(it.hasNext()){ String s = (String)it.next(); System.out.println(s); //输出--西瓜
火龙果 //不允许使用collection.remove();的删除方法,可以使用it.remove(); //it.remove(); } System.out.println(collection.size());//输出结果--2 // * 4.判断 System.out.println("==========================="); System.out.println(collection.contains("西瓜"));//输出--true System.out.println(collection.isEmpty());//输出--false } }
也可以用add()方法添加对象
//假设Student类已经定义好 Student s1 = new Student("爱丽丝",17); Student s2 = new Student("桐人",17); Student s3 = new Student("优吉欧",17); //新建Collection对象 Collection collection = new ArrayList(); //1.添加数据 collection.add(s1); collection.add(s2); collection.add(s3); System.out.println(collection); System.out.println(collection.size());
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端