---------- android培訓、java培訓、期待與您交流! ----------
一、集合框架概述
(一)集合框架中集合類關系簡化圖
(二)為什么出現集合類?
面向對象語言對事物的體現都是以對象的形式,所以為了方便對多個對象的操作,就對對象進行存儲,集合就是用于存儲對象的。
(三)數組和集合類同是容器,有何不同?
、數組長度是固定的;集合長度是可變的。
2、數組中可以存儲基本數據類型,集合只能存儲對象。
(四)集合類的特點
集合可以存儲不同類型的對象。集合只用于存儲對象,集合長度是可變的。
(五)為什么會出現這么多容器?
因為每一個容器對數據的存儲方式都有不同,這個存儲方式稱為數據結構。
二、Collection接口
(一)Collection概述
Collection是集合框架中的常用接口。其下有兩個子接口:List(列表),Set(集)。
所屬關系:Collection
|--List:元素是有序的,元素可以重復。因為有索引(index)。
|--Set:元素是無序的,元素不可以重復,無索引。
(二)Collection接口的常見方法
1、添加
add(Object obj):add方法的參數類型是Object。以便于接收任意類型對象。
addAll(Collection coll):將指定 collection 中的所有元素都添加到此collection中。
2、刪除
clear():清空集合
remove(Object obj):
removeAll(Collection col):移除此 collection 與指定 collection 中的交集元素。
3、判斷
boolean contains(Object obj):判斷collection是否包含obj這個元素
boolean isEmpty():判斷集合是否為空
4、獲取
int size():返回此collection中的元素數。
5、其他
retainAll(Collection coll):保留兩集合的交集元素。
注:集合中存儲的都是對象的引用(地址)。
三、迭代器(iterater)
(一)概述
1、什么是迭代?迭代就是集合的取出元素種方式。
2、集合迭代原理:將“取出方式”定義在集合的內部,這樣“取出方式”就可以直接訪問集合內部的元素,那么“取出方式”就被定義成了內部類。不同的數據結構,“取出方式”的具體實現細節也不相同,但都有共性內容“判斷”和“取出”,將共性的規則抽取出來,即是Iterator。
3、如何獲取集合中的“對象”元素呢?
通過一個對外提供的方法:iterator(),來獲取集合中存儲的對象。因為Collection中有iterator方法,所以Collection的每一個子類集合對象都具備迭代器。
(二)迭代器的方法
1、hasNext():有下一個元素,返回true
2、next():取出下一個元素
3、remove():從迭代器指向的 collection 中移除迭代器返回的最后一個元素
注:在迭代時循環中next調用一次,就要hasNext判斷一次。
4、Iterator的使用方法示例:
ArrayList a = newArrayList();//創建一個集合
Iterator it = a.iterator();//獲取一個迭代器,用于取出集合中的元素。
//方式一:for循環(老外的寫法),好處在于it對象在迭代完成后就釋放了,不占內存。
1 for ( Iterator it = a.iterator() ; it.hasNext(); ){2 System.out.PRintln ( it.next() );3 }
//方式二:while循環
1 while ( it.hasNext() ){2 System.out.println ( it.next() );3 }
(三)迭代器的注意事項
1、迭代器在Collcection接口中是通用的,它替代了Vector類中的Enumeration(枚舉)。
2、迭代器的next()方法是自動向下取元素,要避免出現NoSuchElementException。
3、迭代器的next()方法返回值類型是Object,所以要記得類型轉換。
四、List集合
(一)List集合作用
是可以完成對集合中元素的增、刪、改、查。
* List集合組成
List:
|--Vector:內部是數組數據結構,是同步的。增刪,查詢都很慢!
|--ArrayList:內部是數組數據結構,是不同步的。替代了Vector。查詢的速度快。
|--LinkedList:內部是鏈表數據結構,是不同步的。增刪元素的速度很快。
(二)List集合常見方法
List特有的常見方法,有一個共性特點就是都可以操作角標。
1、添加(增)
void add(index , element):指定位置添加元素
boolean add(index , collection):
2、刪除(刪)
Object remove(index): 刪除指定位置的元素
3、修改(改)
Object set(index,element):修改指定位置的元素
4、獲取(查)
Object get(index):獲取指定角標的元素
int indexOf(object):獲取元素第一次出現的位置,如果沒有則返回-1
int lastIndexOf(object):返回此列表中最后出現的指定元素的索引
List subList(from , to):返回列表中指定的from (包括)到to(不包括)之間的部分。
注:List集合判斷元素是否相同,移除等操作,依據的是元素的equals方法。
(三)ListIterator
1、概述
(1)ListIterator是List集合特有的迭代器,是Iterator的子接口。
(2)在迭代時,不可以通過集合對象的方法操作集合中的元素。因為會發生ConcurrentModificationException異常。所以在迭代器時,只能用迭代器的方法操作元素。可是Iterator方法有限,只能對元素進行判斷、取出、刪除的操作。如果想要其他的操作,如添加、修改等,就需要使用其子接口ListIterrator。該接口只能通過List集合的listIterator()方法獲取。
(3)為什么ListIterator才可以增、刪、改、查?因為List集合中的元素都帶角標。
2、ListIterator特有的方法
void add(obj):為list增加元素
void set(obj):用指定元素替換 next 或 previous 返回的最后一個元素。
boolean hasprevious():判斷前面有沒有元素
Object previous():返回列表中的前一個元素。
(四)Enumeration
1、枚舉是Vector類特有的取出方式。
2、Vector取出元素的方式:(1)迭代器方式取出;(2)for循環遍歷,get方式取;(3)按角標索引取出;(4)枚舉方式取出。
3、特有方法
addElement(obj):添加元素,相當于add(obj);
Enumeration elements():Vector特有取出方式(枚舉)
hasMoreElements():是否還有元素,相當于Iterator的hasNext()方法
nextElements():取出下一個元素,相當于Iterator的next()方法
4、枚舉方法示例:
1 Vector v=new Vector();2 for ( Enumeration en = v.elements() ; e.hasMoreElements() ; ){3 System.out.println(en.nextElements());4 }
(五)LinkedList(實現不同步)
1、LinkedList底層:使用的是“鏈表”結構。
2、特點:增刪速度很快,查詢稍慢。
3、特有方法:
(1)添加:addFirst(); addLast();
(2)獲取:獲取元素,但不刪除元素。
包括:getFirst(); getLast();
(3)刪除:獲取元素,并刪除元素。
包括:removeFirst(); removeLast();
4、JDK1.6后,出現了替代方法。
(1)添加:offerFirst(); offLast();
(2)獲取:獲取元素,但是不刪除。如果集合中沒有元素,會返回null。包括:peekFirst(); peekLast();
(3)刪除:獲取元素,并刪除元素。如果集合中沒有元素,會返回null。包括:pollFirst(); pollLast();
5、LinkList示例練習
/* 使用LinkedList模擬一個堆棧或者隊列數據結構。
堆棧:先進后出 如同一個杯子。
隊列:先進先出 First in First out FIFO 如同一個水管。 */
1 import java.util.*; 2 class LinkedListTest{ 3 public static void main(String[] args) { 4 LinkedList link = new LinkedList(); 5 link.addFirst("java01"); 6 link.addFirst("java02"); 7 l.addFirst("java03"); 8 link.addFirst("java04"); 9 link.addFirst("java05");10 //堆棧輸出11 stack(link);12 //隊列輸出13 queue(link);14 }15 //堆棧16 public static void stack(LinkedList link) {17 while (!link.isEmpty()) {18 sop(link.removeFirst());19 }20 }21 22 //隊列23 public static void queue(LinkedList link){24 while(!link.isEmpty()){25 sop(link.removeLast());26 }27 }28 29 //輸出30 public static void sop(Object obj)31 {32 System.out.println(obj);33 }34 }
五、Set集合
(一)概述
Set:元素是無序(存入和取出的順序不一定一致),元素不可以重復。
|--HashSet:底層數據結構是哈希表,線程不同步。
|--TreeSet:可以對Set集合中的元素進行排序。
(二)HashSet
1、HashSet:保證元素唯一性的原理:判斷元素的hashCode值是否相同。如果相同,還會繼續判斷元素的equals方法,是否為true。
2、Set集合的功能和Collection是一致的。
3、練習:HashSet代碼示例
1 //(1)HashSet示例 2 import java.util.HashSet; 3 import java.util.Iterator; 4 public class HashSetDemo { 5 public static void main(String[] args) { 6 HashSet hs = new HashSet(); 7 hs.add("hehe"); 8 // hs.add("heihei"); 9 hs.add("hahah");10 hs.add("xixii");11 hs.add("hehe");12 Iterator it = hs.iterator();13 while(it.hasNext()){14 System.out.println(it.next());15 }16 }17 }18 //(2)LinkedHashSet代碼示例19 import java.util.HashSet;20 import java.util.Iterator;21 import java.util.LinkedHashSet;22 public class LinkedHashSetDemo {23 public static void main(String[] args) {24 HashSet hs = new LinkedHashSet();25 hs.add("hahah");26 hs.add("hehe");27 hs.add("heihei");28 hs.add("xixii");29 // hs.add("hehe");30 Iterator it = hs.iterator();31 while(it.hasNext()){32 System.out.println(it.next());33 }34 }35 }
(三)TreeSet
1、TreeSet:默認按照字母的自然排序。底層數據結構是二叉樹。保證元素唯一性的依據:compareTo方法return 0。
TreeSet排序有兩種方式:
(1)第一種方式:讓元素自身具備比較性,元素要實現Comparable接口,覆蓋CompareTo方法,這種方式也稱為元素的自然順序,也叫默認順序。代碼示例如下:
1 import java.util.*; 2 //學生類 3 class Student implements Comparable{ 4 private String name; 5 private int age; 6 Student(String name,int age){ 7 this.name=name; 8 this.age=age; 9 }10 public String getName(){11 return name;12 }13 14 public int getAge(){15 return age;16 }17 //復寫hashCode 方法18 public int hashCode(){19 return name.hashCode()+age*39;20 }21 //覆寫equals方法 22 public boolean equals(Object obj){23 if(!(obj instanceof Student))24 throw new RuntimeException();25 Student s = (Student)obj;26 return this.name.equals(s.name)&&this.age==s.age;27 }28 //覆寫compareTo方法 29 public int compareTo(Object obj){30 Student s = (Student)obj;31 if(this.age==s.age)32 return this.name.compareTo(s.name);33 return this.age-s.age;34 }35 }36 37 class TreeSetTest{38 public static void main(String[] args){39 TreeSet<Student> t=new TreeSet<Student>();40 t.add(new Student("zhangsan",22));41 t.add(new Student("lisi",20));42 t.add(new Student("wangwu",19));43 t.add(new Student("zhouliu",19));44 t.add(new Student("zhaoqi",28));45 46 for (Iterator<Student> it=t.iterator(); it.hasNext(); ){47 Student s=it.next();48 System.out.println(s.getName()+"....."+s.getAge());49 }50 }51 }
(2)第二種方式:當元素自身不具備比較性時,或者具備的比較性不是所需要時,這時就需要讓集合自身具備比較性,就需要定義比較器,即定義一個類,實現Comparator接口,覆蓋compare方法。比較器示例代碼如下:
/* 需求: 往TreeSet集合中存儲自定義對象學生, 想按照學生的年齡進行排序。 */
1 import java.util.*; 2 //學生類 3 class Student implements Comparable{ 4 private String name; 5 private int age; 6 Student(String name,int age){ 7 this.name=name; 8 this.age=age; 9 }10 public String getName(){11 return name;12 }13 14 public int getAge(){15 return age;16 }17 //覆寫hashCode方法18 public int hashCode(){19 return name.hashCode()+age*39;20 }21 //覆寫equals方法22 public boolean equals(Object obj){23 if(!(obj instanceof Student))24 throw new RuntimeException();25 Student s = (Student)obj;26 return this.name.equals(s.name)&&this.age==s.age;27 }28 //復寫compareTo以便TreeSet集合調用29 public int compareTo(Object obj){30 Student s=(Student)obj;31 if(this.age==s.age)32 return this.name.compareTo(s.name);33 return this.age-s.age;34 //return new Integer(this.age).compareTo(new Integer(s.age)); 35 }36 }37 38 class TreeSetTest{39 public static void main(String[] args){40 TreeSet<Student> t=new TreeSet<Student>(new LenCompare());41 t.add(new Student("zhangsan",22));42 t.add(new Student("lisi",20));43 t.add(new Student("wangwu",19));44 t.add(new Student("zhouliu",19));45 t.add(new Student("zhaoqi",28));46 47 for (Iterator<Student> it=t.iterator(); it.hasNext(); ){48 Student s=it.next();49 System.out.println(s.getName()+"....."+s.getAge());50 }51 }52 53 }54 //定義比較器,以姓名長度為主要比較55 class LenCompare implements Comparator<Student>{56 public int compare(Student s1,Student s2){57 int num=new Integer(s1.getName().length()).compareTo(new Integer(s2.getName().length()));58 if (num==0){59 return new Integer(s1.getAge()).compareTo(s2.getAge());60 }61 return num;62 }63 }
六、Map集合
(一)概述
Map<K,V>集合是一個接口,和List集合及Set集合不同的是,它是雙列集合。
(二)Map集合子類體系
Map:
|--Hashtable:底層是哈希表數據結構,不可以存入null鍵null值。該集合是線程同步的。JDK1.0,效率低。
|--HashMap:底層是哈希表數據結構。允許使用null鍵null值,該集合是不同步的。JDK1.2,效率高。
|--TreeMap:底層是二叉樹數據結構。線程不同步。可以用于給Map集合中的鍵進行排序。
Map和Set很像。其實Set底層就是使用了Map集合。
(三)Map特點
該集合存儲鍵值對,一對一對往里存,而且要保證鍵的唯一性。
(四)Map集合的常用方法
1、添加
value put(K key,V value):添加元素,如果出現添加時,相同的鍵,那么后添加的值會覆蓋原有鍵對應值,并put方法會返回被覆蓋的值。
void putAll(Map <? extends K,? extends V> m):添加一個集合
2、刪除
clear():清空
value remove(Object key):刪除指定鍵值對
3、判斷
containsKey(Object key):判斷鍵是否存在
containsValue(Object value):判斷值是否存在
isEmpty():判斷是否為空
4、獲取
get(Object key):通過鍵獲取對應的值
size():獲取集合的長度
values():獲取Map集合中所以得值,返回一個Collection集合
5、兩個取出方法
Set<Map.Entry<K , V>> entrySet();
Set<K> keySet();
注:HashMap集合可以通過get()方法的返回值來判斷一個鍵是否存在,通過返回null來判斷。
(五)Map集合的兩種取出方式
Map集合的取出原理:將Map集合轉成Set集合,再通過迭代器取出。
1、Set<K> keySet():將Map集合中所有的鍵存入Set集合。因為Set具備迭代器。所以可以通過迭代方式取出所有鍵,再通過get方法獲取每一個鍵對應的值。示例代碼如下:
1 import java.util.HashMap; 2 import java.util.Iterator; 3 import java.util.Map; 4 public class MapDemo{ 5 public static void main(String[] args){ 6 Map<Integer,String> map = new HashMap<Integer,String>(); 7 map.put(1, "zhangsan"); 8 map.put(2, "lisi"); 9 map.put(3, "wangwu");10 map.put(4, "zhaoliu");11 map.put(5, "zhouqi");12 keyset(map);13 }14 //keySet取出方式15 public static void keyset(Map<Integer,String> hm){16 Iterator<Integer> it = hm.keySet().iterator();17 while(it.hasNext()){18 Integer key = it.next();19 String value = hm.get(key);20 System.out.println(key+":"+value);21 }22 }23 }
2、Set<Map.Entry<K,V>> entrySet():將Map集合中的映射關系存入到Set集合中,而這個關系的數據類型就是:Map.Entry。關于Map.Entry:其實Entry也是一個接口,它是Map的接口中的一個內部接口。示例代碼如下:
1 import java.util.HashMap; 2 import java.util.Iterator; 3 import java.util.Map; 4 import java.util.Set; 5 public class MapDemo{ 6 public static void main(String[] args){ 7 Map<Integer,String> map = new HashMap<Integer,String>(); 8 map.put(1, "zhangsan"); 9 map.put(2, "lisi");10 map.put(3, "wangwu");11 map.put(4, "zhaoliu");12 map.put(5, "zhouqi");13 keyset(map);14 }15 //Map.Entry取出方式16 public static void keyset(Map<Integer,String> hm){17 Set<Map.Entry<Integer,String>> entrySet = hm.entrySet();18 Iterator<Map.Entry<Integer,String>> it = entrySet.iterator();19 20 while(it.hasNext()){21 Map.Entry<Integer, String> me = it.next();22 Integer key = me.getKey();23 String value = me.getValue();24 System.out.println(key+":"+value);25 }26 }27 }
(六)Map集合存儲自定義對象
/* 每一個學生都有對應的歸屬地。
學生Student,地址String。
學生屬性:姓名,年齡。
注意:姓名和年齡相同的視為同一個學生。
保證學生的唯一性。
思路: 1、描述學生類; 2、定義一個Map集合,存儲學生對象和地址值;3、獲取Map中的元素。*/
1 import java.util.HashMap; 2 import java.util.Iterator; 3 import java.util.Set; 4 public class MapDemo { 5 public static void main(String[] args) { 6 /*將學生對象和學生的歸屬地通過鍵與值存儲到map集合中。*/ 7 HashMap<Student,String> hm = new HashMap<Student,String>(); 8 hm.put(new Student("lisi",38),"北京"); 9 hm.put(new Student("zhaoliu",24),"上海");10 hm.put(new Student("xiaoqiang",31),"沈陽");11 hm.put(new Student("wangcai",28),"大連");12 hm.put(new Student("zhaoliu",24),"鐵嶺");13 Iterator<Student> it = hm.keySet().iterator(); 14 while(it.hasNext()){15 Student key = it.next();16 String value = hm.get(key);17 System.out.println(key.getName()+":"+key.getAge()+"---"+value);18 }19 }20 }21 //定義學生類,繼承Person類22 class Student extends Person {23 public Student() {24 super();25 }26 public Student(String name, int age) {27 super(name, age);28 }29 @Override30 public String toString() {31 return "Student:"+getName()+":"+getAge();32 }33 }34 //定義Person類,實現Comparable接口35 class Person implements Comparable<Person> {36 private String name;37 private int age; 38 public Person() {39 super();40 }41 public Person(String name, int age) {42 super();43 this.name = name;44 this.age = age;45 }46 public int compareTo(Person p){47 int temp = this.age - p.age;48 return temp==0?this.name.compareTo(p.name):temp;49 }50 @Override51 public int hashCode() {52 final int prime = 31;53 int result = 1;54 result = prime * result + age;55 result = prime * result + ((name == null) ? 0 : name.hashCode());56 return result;57 }58 @Override59 public boolean equals(Object obj) {60 if (this == obj)61 return true;62 if (obj == null)63 return false;64 if (getClass() != obj.getClass())65 return false;66 Person other = (Person) obj;67 if (age != other.age)68 return false;69 if (name == null) {70 if (other.name != null)71 return false;72 } else if (!name.equals(other.name))73 return false;74 return true;75 }76 public String getName() {77 return name;78 }79 public void setName(String name) {80 this.name = name;81 }82 public int getAge() {83 return age;84 }85 public void setAge(int age) {86 this.age = age;87 }88 @Override89 public String toString() {90 return "Person:"+getName()+":"+getAge();91 }92 }
(七)Map練習
/* 獲取該字符串“jsdfjliwernsdfmxcjfoj”中的每個字母出現的次數,希望打印的結果是:a(1)b(2)..... */
1 import java.util.*; 2 class CharCount { 3 public static void main(String[] args) { 4 String str = "jsdfjliwernsdfmxcjfoj"; 5 System.out.println("str中各字母出現的次數:" + charCount(str)); 6 } 7 // 定義一個方法獲取字符串中字母出現的次數 8 public static String charCount(String str) { 9 char[] cha = str.toCharArray();// 轉換為字符數組10 // 定義一個TreeMap集合,因為TreeMap集合會給鍵自動排序11 TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();12 int count = 0;// 定義計數變量13 for (int x = 0; x < cha.length; x++) {14 if (!(cha[x] >= 'a' && cha[x] <= 'z' || cha[x] >= 'A'15 && cha[x] <= 'Z'))16 continue;// 如果字符串中非字母,則不計數17 Integer value = tm.get(cha[x]);// 獲取集合中的值18 if (value != null)// 如果集合中沒有該字母,則存入19 count = value;20 count++;21 tm.put(cha[x], count);// 存入鍵值對22 count = 0;// 復位計數變量23 }24 StringBuilder sb = new StringBuilder();// 定義一個容器25 // 遍歷集合,取出并以題目格式存入容器中26 for (Iterator<Character> it = tm.keySet().iterator(); it.hasNext();) {27 Character ch = it.next();28 Integer value = tm.get(ch);29 sb.append(ch + "(" + value + ")");30 }31 return sb.toString();// 返回字符串32 }33 }
七、集合的一些技巧
需要唯一嗎?
|——需要:Set
| 需要制定順序嗎?
| |——需要:TreeSet
| |——不需要:HashSet
| 但是要想要一種存儲一致的順序,用LinkedHashSet。
|
|——不需要:List
| 需要頻繁增刪嗎?
| |——需要:LinkedList
| |——不需要:ArrayList
---------- android培訓、java培訓、期待與您交流! ----------
|
新聞熱點
疑難解答