Collection 接口是層次結構中的根接口。Collection 表示一組對象,這些對象也稱爲 Collection 的元素。Collection 接口是List 接口與 Set 接口的父接口,通常情況下不被直接使用。在Collection 接口中定義了一些通用的方法,通過這些方法可以實現對集合的基本操作,因爲 List 接口和 Set 接口中實現了Collection 接口,所以這些方法對 List 集合和 Set 集合是通用的。
1,add方法:
public class Append{ public static void main(String[] args) { Collection list = newArrayList(); //實例化集合類對象 list.add("apple"); //向集合添加數據 list.add("orange"); list.add("pear"); Iterator it = list.iterator(); //創建迭代器 System.out.println("集合中的元素有:"); while (it.hasNext()) { //判斷是否有下一個元素 String str = (String)it.next();//獲取集合中的元素 System.out.println(str); } } } |
2,addAll方法:
public classAddGather { public static void main(String[] args) { String apple = "apple"; String orange = "orange"; String pear = "pear"; Collection<String> list = newArrayList<String>(); list.add(apple); //通過add()方法添加指定對象到集合中 list.add(orange); list.add(pear); Collection<String> list2 = newArrayList<String>(); //通過addAll()方法添加指定集合中的所有對象到該集合中 list2.addAll(list); Iterator<String> it = list2.iterator(); //通過iterator()方法序列化集合中的所有對象 System.out.println("集合中的對象爲:"); while (it.hasNext()) { String str = it.next(); //因爲對實例it進行了泛化,所以不需要進行強制類型轉換 System.out.println(str); } } } |
3,iterator方法
public classIterativePractice { public static void main(String[] args) { Collection<String> collection= new ArrayList<String>(); //創建集合對象 collection.add("Java"); //向集合中添加對象 collection.add("C#"); collection.add("VB"); Iterator<String> it =collection.iterator(); //創建集合對象的迭代器 System.out.println("集合中的元素爲:"); while(it.hasNext()){ //循環遍歷迭代器 String element =(String)it.next(); //獲取集合中的每個元素 System.out.println(element); //將集合中的元素輸出 } } } |
4,romoveAll方法
public cla***emoveCollection { public static void main(String[] args) { Collection<String> list = newArrayList<String>(); //定義Collection集合對象 list.add("Java編程詞典"); //使用add()方法向集合中添加對象 list.add("C++編程詞典"); list.add("VB編程詞典"); list.add("C#編程詞典"); list.add(".net編程詞典"); Iterator<String> it =list.iterator(); //創建集合對象的迭代器 System.out.println("集合中原有的對象爲:"); while (it.hasNext()) { //循環遍歷集合對象 String obj = (String)it.next(); //獲取集合中的各個元素 System.out.println(obj); //將集合中的對象輸出 } Collection<String> list2 = newArrayList<String>(); //定義集合對象 list2.add(".net編程詞典"); //向集合中添加對象 list2.add("C#編程詞典"); list.removeAll(list2); Iterator<String> it2 =list.iterator(); //獲取去除指定集合元素後的集合迭代器 System.out.println("移除指定對象後集閤中的對象爲:"); while (it2.hasNext()) { //循環遍歷集合對象 String obj = (String)it2.next(); //獲取集合中的元素對象 System.out.println(obj); //將集合中的對象輸出 } } } |
5,isEmpty方法
public classSizeStat { public static void main(String[] args) { Collection<String> collection =new ArrayList<String>(); //定義集合對象 collection.add("hello"); //使用add()方法向集合中添加元素 collection.add("你好"); collection.add("很高興認識你"); if(!collection.isEmpty()){ //判斷集合是否爲空 System.out.println("該集合不爲空,集合中的元素爲:"); Iterator<String> it =collection.iterator(); //創建集合迭代器 while(it.hasNext()){ //循環遍歷迭代器 System.out.println(it.next()); //輸出集合中的元素 } } } } |