1、定義:Java集合類存放於java.util包,是存放對象的容器,長度可變,只能存放對象,可以存放不同的數據類型;
2、常用集合接口:
a、Collection接口:最基本的集合接口,存儲不唯一,無序的對象,List接口和Set接口的父接口;
b、List接口:一個有序、可以重復的集合,常用實現類ArrayList和LinkedList;
1 // 底層數據結構是數組,查詢快,增刪慢,線程不安全,效率高 2 List arrayList = new ArrayList(); 3 // 底層數據結構是數組,查詢快,增刪慢,線程安全,效率低,耗性能 4 List vector = new Vector(); 5 // 底層數據結構是鏈表,查詢慢,增刪快,線程不安全,效率高 6 List linkedList = new LinkedList();
c、Set接口:一個無序、不可重復的集合,常用實現類HashSet、LinkedHashSet、TreeSet;
1 // 元素無序,不可重復,線程不安全,集合元素可以為 NULL 2 Set hashSet = new HashSet(); 3 // 底層采用鏈表和哈希表的算法,保證元素有序,唯一性(即不可以重復,有序),線程不安全 4 Set linkedHashSet = new LinkedHashSet(); 5 // 底層使用紅黑樹算法,擅長於范圍查詢,元素有序,不可重復,線程不安全 6 Set treeSet = new TreeSet();
d、Map接口:key-value的鍵值對,key不允許重復,value可以,key-value通過映射關系關聯,常用實現類HashMap和TreeMap;
1 // 采用哈希表算法,key無序且不允許重復,key判斷重復的標准是:key1和key2是否equals為true,並且hashCode相等 2 Map<String, String> hashMap = new HashMap<String, String>(); 3 // 采用紅黑樹算法,key有序且不允許重復,key判斷重復的標准是:compareTo或compare返回值是否為0 4 Map<String, String> treeMap = new TreeMap<String, String>();
3、Set和List的區別:
a、Set實例存儲是無序的,不重復的數據;List實例存儲的是有序的,可以重復的元素;
b、Set檢索效率低下,刪除和插入效率高,刪除和插入不會引起元素位置改變;
c、List可以根據存儲的數據長度自動增長List長度,查找元素效率高,插入刪除效率低,插入和刪除時會引起其他元素位置改變;
4、Map和Set的關系:
a、HashMap、HashSet 都采哈希表算法,TreeMap、TreeSet 都采用紅黑樹算法、LinkedHashMap、LinkedHashSet 都采用哈希表算法和紅黑樹算法;
b、分析Set的底層源碼,Set 集合就是由Map集合的Key組成;
5、集合遍歷:
1 // 遍歷List 2 List<String> lst = new ArrayList<String>(); 3 lst.add("apple"); 4 lst.add("banana"); 5 // 第一種 6 for(int i = 0; i < lst.size(); i++){ 7 System.out.println(lst.get(i)); 8 } 9 // 第二種 10 for(String str : lst){ 11 System.out.println(str); 12 } 13 // 第三種 迭代器 14 Iterator it = lst.iterator(); 15 while(it.hasNext()){ 16 System.out.println(it.next()); 17 } 18 19 // 遍歷Map 20 Map<String, String> map = new HashMap<String, String>(); 21 map.put("apple", "蘋果"); 22 map.put("banana", "香蕉"); 23 // 第一種 24 for(String key : map.keySet()){ 25 System.out.println(key + "——" + map.get(key)); 26 } 27 // 第二種 推薦使用尤其是數據量大時 28 for(Entry<String, String> entry : map.entrySet()){ 29 System.out.println(entry.getKey() + "——" + entry.getValue()); 30 } 31 // 第三種 迭代器 32 Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); 33 while(iterator.hasNext()){ 34 Entry<String, String> entry = iterator.next(); 35 System.out.println(entry.getKey() + "——" + entry.getValue()); 36 } 37 // 第四種 無法取到key值 38 for(String val : map.values()){ 39 System.out.println(val); 40 }
