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(): 把集合中的元素,存儲到數組中。

import java.util.ArrayList;

import java.util.Collection;

public class Demo1Collection {

    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("掃地僧"));
    
        //boolean remove(E e) 刪除在集合中的o元素
        System.out.println("刪除石破天:"+coll.remove("石破天"));
        System.out.println("操作之後集合中元素:"+coll);
    
        // size() 集合中有幾個元素
        System.out.println("集合中有"+coll.size()+"個元素");
    
        // Object[] toArray()轉換成一個Object數組
        Object[] objects = coll.toArray();
        // 遍歷數組
        for (int i = 0; i < objects.length; i++) {
            System.out.println(objects[i]);
        }
    
        // void  clear() 清空集合
        coll.clear();
        System.out.println("集合中內容爲:"+coll);
        // boolean  isEmpty()  判斷是否爲空
        System.out.println(coll.isEmpty());     
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章