接口Collection

接口Collection

Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。方法如下:

  • 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(): 把集合中的元素,存储到数组中。

备注: 有关Collection中的方法可不止上面这些,其他方法可以自行查看API学习。

代码举例

package demo01;

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo01 {
    public static void main(String[] args) {
        // 创建集合对象
        // 使用多态形式
        Collection<String> coll = new ArrayList<String>();
        // 使用方法
        // 添加功能  boolean  add(String s)
        coll.add("张三");
        coll.add("李四");
        coll.add("王五");
        System.out.println(coll);//[张三, 李四, 王五]
        // boolean contains(E e) 判断o是否在集合中存在
        System.out.println("判断  张三 是否在集合中" + coll.contains("张三"));//判断  张三 是否在集合中true
        //boolean remove(E e) 删除在集合中的o元素
        System.out.println("删除李四:" + coll.remove("李四"));//删除李四:true
        System.out.println("操作之后集合中元素:" + coll);//操作之后集合中元素:[张三, 王五]
        // size() 集合中有几个元素
        System.out.println("集合中有" + coll.size() + "个元素");//集合中有2个元素
        // Object[] toArray()转换成一个Object数组
        Object[] objects = coll.toArray();
        // 遍历数组
        for (int i = 0; i < objects.length; i++) {
            System.out.print(objects[i] + " ");//张三 王五
        }
        // void  clear() 清空集合
        coll.clear();
        System.out.println("集合中内容为:" + coll);//集合中内容为:[]
        // boolean  isEmpty()  判断是否为空
        System.out.println(coll.isEmpty());//true
    }
}

猜你喜欢

转载自www.cnblogs.com/wurengen/p/10915822.html