集合類的由來,
對象用於封閉特有數據,對象多了需要存儲,如果對象的個數不確定就使用集合容器進行存儲。
集合特點:
1.用於存儲對象的容器。
2.集合的長度是可變的。
3.集合中不可以存儲基本數據類型值。
集合容器因為內部的數據結構不同,有多種具體容器。
不斷的向上抽取,就形成了集合框架。
collection的常見方法:
1.添加
boolean add(Object obj); --添加
boolean addAll(Collection coll) --添加集合
2.刪除
boolean remove(Ooject obj); --刪除
boolean remove(Collection coll) --刪除集合
void clear() --移除所有內容
3.判斷
boolean contains(object obj); --判斷些集合指定的元素,則返回true
boolean containsAll(Collection coll) --判斷些集合指定的合集,則返回true
boolean isEmpty(): --判斷集合中是否有元素。
4.獲取:
int size(); --返回集合中的元素數
Iterator iterator(); --取出元素的方式:迭代器
5.其他:
boolean retainAll(Collection coll) --取交集(1,2,5; 2,4; 取2)
Object[] toArray(): --將集合轉成數組。
測試:
package demo_liu.test.collection; import java.util.ArrayList; import java.util.Collection; public class t1 { public static void main(String[] args) { Collection coll = new ArrayList(); //調用Collection show(coll); Collection c1 = new ArrayList(); Collection c2 = new ArrayList(); //調用Collection show(c1,c2); } public static void show(Collection c1,Collection c2) { //給c1添加元素 c1.add("1123"); c1.add("11234"); c1.add("45345"); c1.add("4564"); c1.add("6753"); //給c2添加元素 c2.add("1123"); c2.add("abc1"); c2.add("abc1"); c2.add("abc1"); c2.add("abc1"); //輸出 System.out.println("c1+"+c1); System.out.println("c2"+c2); //演示addAll() 添加集合 c1.addAll(c2); //演示removeAll 刪除集合:true // boolean b= c1.removeAll(c2);//將兩個集合中的相同元素從調用RemoveAll的集合中刪除例:c2.add("1123"); // System.out.println("removAll"+b);//輸出 :c1[11234, 45345, 4564, 6753] //C1:中少了c1.add("1123"); //演示retainAll // boolean c = c1.retainAll(c2);//取交集:指兩個集合中共有的數據 // System.out.println("c1"+c1); //保留和指定的集合相同的元素,而刪除不同的元素。 //和removeAll功能相反。 //輸入:c1[1123, 1123, abc1, abc1, abc1, abc1] //演示ContainsAll boolean n = c1.containsAll(c2);//包含:c1中包含c2的所有元素,沒有則返回false System.out.println(n); System.out.println("c1"+c1); } public static void show(Collection coll) { //1. 添加元素 coll.add("123"); coll.add("木頭人"); coll.add("汐"); System.out.println("輸出所有元素"+coll); //輸出所有元素[123, 木頭人, 汐] System.out.println("是否包含:"+coll.contains("123")); //是否包含:true System.out.println("個數:"+coll.size()); //個數:3 //刪除‘123’:輸出 coll.remove("123"); //[木頭人, 汐] System.out.println(coll); //清空集合 coll.clear(); System.out.println("清空元素:"+coll); //清空元素:[] System.out.println("是否有元素:"+coll.isEmpty()); //是否有元素:true //着邊和清空有沒有關系, 我們先查詢集合是否有元素,則返回true,再清空后,也是返回true; } }