进阶day02-Collection接口常用方法(单列集合)

This commit is contained in:
2026-01-29 11:32:00 +08:00
parent e65d4187ee
commit b1b3212413

View File

@@ -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<String> 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
}
}