java.util.Collection接口 作用: 所有单列集合最顶层的接口,里面定义了所有单列集合共性的方法 任意的单列集合都可以使用Collection接口中的方法 1.创建集合对象,使用多态
Collection<String> coll = new ArrayList<>(); coll.add("李四"); coll.add("胡歌"); coll.add("艾克"); coll.add("德玛"); System.out.println(coll);//[李四,胡歌,艾克,德玛]2.public boolean add(E e):把给定的对象添加到当前集合中(返回值为boolean值)
boolean a = coll.add("张三"); System.out.println(a);//ture System.out.println(coll);//[李四,胡歌,艾克,德玛,张三]3.public boolean remove(E e):把给定的对象在当前集合中删除(返回值为boolean: 集合中存在元素,删除元素,返回ture ,集合中不存在则返回false)
//删除存在的元素李四 boolean b = cool.remove("李四"); System.out.println(b);//true System.out.println(coll);//[胡歌,艾克,德玛,张三] //删除不存在的元素迪迦 boolean c = cool.remove("迪迦"); System.out.println(c);//false System.out.println(coll);//[李四,胡歌,艾克,德玛,张三]4.public boolean contains(E e): 判断当前集合中是否包含给定的对象(包含返回true 不包含返回false)
//判断胡歌是否存在 Boolean d = cool.contains("胡歌"); System.out.println(d);//ture //判断亚索是否存在 Boolean e = cool.contains("亚索"); System.out.println(e);//ture5.public boolean isEmpty(): 判断当前集合是否为空
boolean f = coll.isEmpt(); System.out.println(f);//false6.public boolean size(): 返回集合中元素的个数
boolean g = cool.size(); System.out.println(g);//47.public Object[] toArray(): 把集合中的元素,存储到数组中
//因为数组数据类型不同,所以要将它改为泛型Object[],它可以存储任意类型 Object[]arr = cool.toArray(); //使用否循环遍历元素 arr.length为集合长度 for(int i = 0;i < arr.length; i++){ System.out.println(arr[i]);//胡歌,艾克,德玛,张三 }8.public void clear(): 清空集合中所有元素,但不删除集合
cool.clear(); System.out.println(cool);//[]