標籤:iter dem 集合 示範 class span java集合 als abc
Collection介面中的共性功能
1.添加
boolean add(object obj);一次添加一個
boolean addAll(Collection);將指定容器中的所有元素添加
2.刪除
void clear();
boolean removbe(object o);
boolean removeAll(Collection c);
3.擷取長度
int size()
4.判斷
boolean isEmpty();
boolean contains(object o)
boolean contains(object)
5.將集合轉成數組
toArray();
toArray([]);
5.取出集合元素iterator
Iterator iterator()
擷取集合中元素上迭代功能的迭代器對象
迭代:取出元素的一種方式
迭代器:具備著迭代功能的對象
而迭代器對象不需要new 直接通過 iterator()擷取即可。
迭代器是取出collection集合元素中的公用方法
package com.runoob.test;import java.util.ArrayList;import java.util.Collection;public class CollectionDemo { public static void main(String[] args) { /* * 示範Collection中的準系統 * */ Collection c1=new ArrayList(); Collection c2=new ArrayList(); /* * 添加單個元素(對象) */ c1.add("abc1"); c1.add("abc2"); c1.add("abc3"); c2.add("abc1"); c2.add("abc2"); c2.add("abc7"); // System.out.println("c1 contains \"abc1\"="+c1.contains("abc1"));//結果為true// System.out.println("c1 contains \"abc\"="+c1.contains("abc"));//結果為false// System.out.println(c1.remove("abc1"));//結果為true,代表刪除成功// System.out.println(c1.remove("abc"));//結果為false,代表刪除失敗 // c1.clear();//清空c1// System.out.println(c1);//結果為[]// System.out.println(c1.isEmpty());結果為true // c1.remove("abc1");// System.out.println(c1);//[abc2,abc3] int a=c1.size(); System.out.println(a); //======帶all的方法======= // c1.removeAll(c2);// System.out.println(c1);//結果為[abc3],刪除c1中和c2相同的部分 // c1.retainAll(c2);// System.out.println(c1);//結果為[abc1,abc2],返回c1和c2的交集 // // c1.addAll(c2);// System.out.println(c1);//結果為[abc1, abc2, abc3, abc1, abc2, abc7]// boolean b=c1.containsAll(c2);// System.out.println(b);//結果為true }}
java集合架構初探