二、Collection常用功能
Collection是所有单列集合的父接口,因此在Collection接口中定义了单列集合(List和Set)通用的一些方法,这些方法可以操作于所有的单列集合。方法如下:
public class demoCollection { public static void main(String[] args) { /* public boolean add(E e): 把给定的对象添加到当前集合中 返回值是一个boolean值,一般都返回true 所以不用接收 */ // 创建集合对象 可以使用多态 Collection<String> coll=new ArrayList<>(); System.out.println(coll);//重写了toString方法[] coll.add("张三"); coll.add("李四"); coll.add("王五"); coll.add("赵六"); System.out.println(coll);//[张三, 李四, 王五, 赵六] } }
import java.util.ArrayList; import java.util.Collection; /** * @author :CaiCai * @date : 2022/4/12 14:46 */ public class demoCollection { public static void main(String[] args) { /* public boolean add(E e): 把给定的对象添加到当前集合中 返回值是一个boolean值,一般都返回true 所以不用接收 */ // 创建集合对象 可以使用多态 Collection<String> coll=new ArrayList<>(); System.out.println(coll);//重写了toString方法[] coll.add("张三"); coll.add("李四"); coll.add("王五"); coll.add("赵六"); System.out.println(coll);//[张三, 李四, 王五, 赵六] /* public boolean remove (E e):把给定的对象在当前集合中删除 返回值是一个布尔值,集合存在元素,删除元素,返回true 集合中不存在元素,删除失败,返回false */ boolean b2=coll.remove("赵六"); System.out.println(b2);//true boolean b3=coll.remove("赵五"); System.out.println(b3);//false /* public boolean contains(E e):判断当前集合中是否包含给定的对象 包含返回true 不包含返回false */ boolean b4=coll.contains("张三"); System.out.println(b4); //public boolean isEmpty():判断当前集合是否为空, 集合为空返回false不为空true boolean b6=coll.isEmpty(); System.out.println(b6);//false //public int size():返回集合中元素的个数 int size=coll.size(); System.out.println(size);//3 //public Object[] toString(); Object[] arr=coll.toArray(); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } //public void clear():清空集合当中的所有元素,但是不删除集合 集合还存在 coll.clear(); System.out.println(coll); } }