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>();
coll.add("小李廣");
coll.add("掃地僧");
coll.add("石破天");
System.out.println(coll);
System.out.println("判斷 掃地僧 是否在集合中"+coll.contains("掃地僧"));
System.out.println("刪除石破天:"+coll.remove("石破天"));
System.out.println("操作之後集合中元素:"+coll);
System.out.println("集合中有"+coll.size()+"個元素");
Object[] objects = coll.toArray();
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
coll.clear();
System.out.println("集合中內容爲:"+coll);
System.out.println(coll.isEmpty());
}
}