From b1b3212413e38a0cd8fb74c3c21f2c4d96f3d8b7 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Thu, 29 Jan 2026 11:32:00 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E9=98=B6day02-Collection=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=B8=B8=E7=94=A8=E6=96=B9=E6=B3=95=EF=BC=88=E5=8D=95?= =?UTF-8?q?=E5=88=97=E9=9B=86=E5=90=88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inmind/collection01/CollectionDemo01.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 javaSE-day02/src/com/inmind/collection01/CollectionDemo01.java diff --git a/javaSE-day02/src/com/inmind/collection01/CollectionDemo01.java b/javaSE-day02/src/com/inmind/collection01/CollectionDemo01.java new file mode 100644 index 0000000..bbc3e46 --- /dev/null +++ b/javaSE-day02/src/com/inmind/collection01/CollectionDemo01.java @@ -0,0 +1,58 @@ +package com.inmind.collection01; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +/* + 3.Collection接口常用方法 + + public boolean add(E e) : 把给定的对象添加到当前集合中 。 + public void clear() :清空集合中所有的元素。 + public boolean remove(E e) : 把给定的对象在当前集合中删除。 + public boolean contains(E e) : 判断当前集合中是否包含给定的对象。 + public boolean isEmpty() : 判断当前集合是否为空。 + public int size() : 返回集合中元素的个数。 + public Object[] toArray() : 把集合中的元素,存储到数组中。 + */ +public class CollectionDemo01 { + public static void main(String[] args) { + //如果单列集合接口Collection不写泛型,默认是object(不推荐) + Collection list = new ArrayList<>(); + list.add("hh"); + list.add(1);//Integer + list.add(true);//Boolean + + //创建一个保存字符串的单列集合 + Collection strList = new ArrayList<>();//多态,编译看左边,运行看右边 + strList.add("张三"); + strList.add("李四"); + strList.add("王五"); + System.out.println(strList);//本质:打印strList的toString方法返回的内容 + //删除指定内容 + boolean removed = strList.remove("赵六"); + System.out.println(removed);//false + removed = strList.remove("张三"); + System.out.println(removed);//true + System.out.println(strList); + + //判断是否包含指定内容 + System.out.println(strList.contains("李四"));//true + + //判断集合中是否为空 + System.out.println(strList.isEmpty());//false + + //获取集合的长度,常用于判断集合是否有内容 + System.out.println(strList.size());//2 + + //将单列集合中的数据,存储到数组(单列集合与数组的转换) + Object[] array = strList.toArray(); + System.out.println(Arrays.toString(array));//[李四, 王五] + + //集合的清除 + strList.clear(); + System.out.println(strList); + System.out.println(strList.isEmpty());//true + + } +}