資料結構:資料的存盤方式,
*
* Collection:是集合的頂層介面,它的子體系有重復的,有唯一的,有有序的,有無序的,(后面會慢慢的講解)
*
* Collection的功能概述:
* 1:添加功能
* boolean add(Object obj):添加一個元素
* boolean addAll(Collection c):添加一個集合的元素
* 2:洗掉功能
* void clear():移除所有元素
* boolean remove(Object o):移除一個元素
* boolean removeAll(Collection c):移除一個集合的元素(是一個還是所有)
* 3:判斷功能
* boolean contains(Object o):判斷集合中是否包含指定的元素
* boolean containsAll(Collection c):判斷集合中是否包含指定的集合元素(是一個還是所有)
* boolean isEmpty():判斷集合是否為空
* 4:獲取功能
* Iterator<E> iterator()(重點)
* 5:長度功能
* int size():元素的個數
* 面試題:陣列有沒有length()方法呢?字串有沒有length()方法呢?集合有沒有length()方法呢?
* 6:交集功能
* boolean retainAll(Collection c):兩個集合都有的元素?思考元素去哪了,回傳的boolean又是什么意思呢?
* 7:把集合轉換為陣列
* Object[] toArray()
package Day15; import java.util.ArrayList; import java.util.Collection; public class JiHe { public static void main(String[] args) { //創建集合物件 //介面無法直接實體化 // Collection c = new Collection(); //創建集合Collection介面的實作需通過實作子類 //其中ArrayList就是其實作其Collection集合的子類 //創建集合物件 Collection c = new ArrayList(); //利用物件呼叫方法---添加功能 c.add("趙同剛"); c.add("朱慶娜"); //輸出查看 System.out.println(c); //洗掉功能 //c.clear();---洗掉全部 //c.remove("朱慶娜");//---洗掉單個集合內的元素 System.out.println(c); //判斷集合中是否包含指定元素 boolean sm= c.contains("朱慶娜"); boolean sm1= c.contains("王"); System.out.println(sm1); //判斷集合是否為空 System.out.println(c.isEmpty()); //獲取集合中元素的個數 System.out.println(c.size()); } }
boolean addAll(Collection c):添加一個集合的元素---添加元素不變
* boolean removeAll(Collection c):移除一個集合的元素(是一個還是所有)
A:移除的是a1和a2中共有的元素---------且只移除a1中的重復元素
* boolean containsAll(Collection c):判斷集合中是否包含指定的集合元素(所有)
* boolean retainAll(Collection c):兩個集合都有的元素?思考元素去哪了,回傳的boolean又是什么意思呢?
1 public class CollectionDemo2 { 2 public static void main(String[] args) { 3 // 創建集合1 4 Collection c1 = new ArrayList(); 5 c1.add("abc1"); 6 c1.add("abc2"); 7 c1.add("abc3"); 8 c1.add("abc4"); 9 10 // 創建集合2 11 Collection c2 = new ArrayList(); 12 // c2.add("abc1"); 13 // c2.add("abc2"); 14 // c2.add("abc3"); 15 // c2.add("abc4"); 16 c2.add("abc5"); 17 c2.add("abc6"); 18 c2.add("abc7"); 19 20 // boolean addAll(Collection c):添加一個集合的元素 21 // System.out.println("addAll:" + c1.addAll(c2)); 22 23 //boolean removeAll(Collection c):移除一個集合的元素(是一個還是所有) 24 //只要有一個元素被移除了,就回傳true, 25 //System.out.println("removeAll:"+c1.removeAll(c2)); 26 27 //boolean containsAll(Collection c):判斷集合中是否包含指定的集合元素(是一個還是所有) 28 //只有包含所有的元素,才叫包含 29 // System.out.println("containsAll:"+c1.containsAll(c2)); 30 31 //boolean retainAll(Collection c):兩個集合都有的元素?思考元素去哪了,回傳的boolean又是什么意思呢? 32 //假設有兩個集合A,B, 33 //A對B做交集,最終的結果保存在A中,B不變, 34 //回傳值表示的是A是否發生過改變, 35 System.out.println("retainAll:"+c1.retainAll(c2)); 36 37 System.out.println("c1:" + c1); 38 System.out.println("c2:" + c2); 39 } 40 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445861.html
標籤:Java
上一篇:集合框架--物件陣列的概述和使用
