Java中的集合框架大類可分為Collection和Map;兩者的區別如下:
Collection是單列集合;Map是雙列集合
Collection中只有Set系列要求元素唯壹;Map中鍵需要唯壹,值可以重復
Collection的數據結構是針對元素的;Map的數據結構是針對鍵的
二、Collection體系:collection包括兩大體系,List和Set
List的特點:
List代表壹個元素有序、且可重復的集合,集合中的每個元素都有其對應的順序索引。
List允許使用重復元素,可以通過索引來訪問指定位置的集合元素。
List默認按元素的添加順序設置元素的索引。
List集合裏添加了壹些根據索引來操作集合元素的方法
Set的特點:存取無序,元素不可以重復
List集合:下面有ArrayList,LinkedList,Vector(已過時)
集合的的最大目的就是為了存取;List集合的特點就是存取有序,可以存儲重復的元素,可以用下標進行元素的操作。
ArrayList:底層是使用數組實現,所以查詢速度快,增刪速度慢
publicstaticvoidmain(String[]args){//使用ArrayList進行添加和遍歷List<String>list=newArrayList<String>();list.add("a");list.add("b");list.add("c");//第壹種遍歷方式,使用叠代器Iterator<String>it=list.iterator();while(it.hasNext()){Stringnext=it.next();System.out.println(next);}System.out.println("-------------------");//第二種遍歷方式,使用foreachfor(Stringstr:list){System.out.println(str);}}LinkedList:是基於鏈表結構實現的,所以查詢速度慢,增刪速度快,提供了特殊的方法,對頭尾的元素操作(進行增刪查)。
使用LinkedList來實現棧和隊列;棧是先進後出,而隊列是先進先出
packageorg.example.test;importjava.util.LinkedList;/***利用LinkedList來模擬棧*棧的特點:先進後出*/publicclassTest12{privateLinkedList<String>linkList=newLinkedList<String>();//壓棧publicvoidpush(Stringstr){linkList.addFirst(str);}//出棧publicStringpop(){returnlinkList.removeFirst();}//查看publicStringpeek(){returnlinkList.peek();}//判斷是否為空publicbooleanisEmpty(){returnlinkList.isEmpty();}}classTest13{publicstaticvoidmain(String[]args){//測試棧Test12test12=newTest12();test12.push("我是第1個進去的");test12.push("我是第2個進去的");test12.push("我是第3個進去的");test12.push("我是第4個進去的");test12.push("我是第5個進去的");//取出while(!test12.isEmpty()){Stringpop=test12.pop();System.out.println(pop);}//打印結果/*我是第5個進去的我是第4個進去的我是第3個進去的我是第2個進去的我是第1個進去的*/}}LinkedList實現Queue:
packageorg.example.test;importjava.util.LinkedList;/***利用linkedList來實現隊列*隊列:先進先出*/publicclassTest12{privateLinkedList<String>link=newLinkedList<String>();//放入publicvoidput(Stringstr){link.addFirst(str);}//獲取publicStringget(){returnlink.removeLast();}//判斷是否為空publicbooleanisEmpty(){returnlink.isEmpty();}}classTest13{publicstaticvoidmain(String[]args){//測試隊列Test12queue=newTest12();queue.put("我是第1個進入隊列的");queue.put("我是第2個進入隊列的");queue.put("我是第3個進入隊列的");queue.put("我是第4個進入隊列的");//遍歷隊列while(!queue.isEmpty()){Stringstr=queue.get();System.out.println(str);}//打印結果/*我是第1個進入隊列的我是第2個進入隊列的我是第3個進入隊列的我是第4個進入隊列的*/}}Vector:因為已經過時,被ArrayList取代了;它還有壹種叠代器通過vector.elements()獲取,判斷是否有元素和取元素的方hasMoreElements()nextElement()。
publicstaticvoidmain(String[]args){Vector<String>vector=newVector<>();vector.add("a");vector.add("v");vector.add("d");Enumeration<String>elements=vector.elements();while(elements.hasMoreElements()){StringnextElement=elements.nextElement();System.out.println(nextElement);}}還有壹些基本操作:
publicstaticvoidmain(String[]args){List<String>list=newArrayList<String>();list.add("b");//第壹個,索引下標0list.add("d");//索引下標1list.add("c");//索引下標2list.add("a");//索引下標3list.add("d");//允許使用重復元素System.out.println(list);//結果:[b,d,c,a,d]System.out.println(list.get(2));//通過索引來訪問指定位置的集合元素.結果:clist.add(1,"f");//在指定索引下標的位置插入數據System.out.println(list);//結果:[b,f,d,c,a,d]List<String>m=newArrayList<String>();m.add("123");m.add("456");list.addAll(2,m);//在指定索引下標的位置插入集合System.out.println(list);//結果:[b,f,123,456,d,c,a,d]System.out.println(list.indexOf("d"));//獲取指定元素在集合中第壹次出現的索引下標.結果:4System.out.println(list.lastIndexOf("d"));//獲取指定元素在集合中最後壹次出現的索引下標.結果:7list.remove(2);//根據指定的索引下標移除元素System.out.println(list);//結果:[b,f,456,d,c,a,d]list.set(1,"ff");//根據指定的索引下標修改元素System.out.println(list);//結果:[b,ff,456,d,c,a,d]//根據索引下標的起始位置截取壹段元素形參壹個新的集合,截取的時候,包含開始的索引不包含結束時的索引List<String>sublist=list.subList(2,4);//取索引下標在大於等於2,小於4的元素System.out.println(sublist);//結果:[456,d]System.out.println(list.size());//集合的長度.結果:7}set集合:Set集合下面有:HashSet,LinkedHashSet,TreeSet
Set集合的特點:元素不重復,存取無序,無下標
HashSet:publicstaticvoidmain(String[]args){//利用HashSet來存取Set<String>set=newHashSet<String>();set.add("a");set.add("b");set.add("b");set.add("c");//遍歷第壹種方式叠代器Iterator<String>it=set.iterator();while(it.hasNext()){Stringstr=it.next();System.out.println(str);}System.out.println("--------------");for(Stringstr:set){System.out.println(str);}//打印結果,重復的已經去掉了/*abc--------------abc*/}HashSet按Hash算法來存儲集合中的元素,因此具有很好的存取和查找性能。HashSet具有以下特點:
不能保證元素的排列順序
不可重復(hashcode不相同)
HashSet不是線程安全的
集合元素可以使null
當向HashSet集合中存入壹個元素時,HashSet會調用該對象的hashCode()方法來得到該對象的hashCode值,然後根據hashCode值決定該對象在HashSet中的存儲位置,存在set集合哪個位置由這個值的hashcode決定,而不是按先來後到。如果兩個元素的equals()方法返回true,但它們的hashCode()返回值不相等,hashSet將會把它們存儲在不同的位置,但依然可以添加成功。
演示HashSet來存儲自定義對象:
packageorg.example.test;publicclassPerson{//屬性privateStringname;privateintage;//構造方法publicPerson(){super();}publicPerson(Stringname,intage){super();this.name=name;this.age=age;}//要讓哈希表存儲不重復的元素,就必須重寫hasCode和equals方法@OverridepublicinthashCode(){finalintprime=31;intresult=1;result=prime*result+age;result=prime*result+((name==null)?0:name.hashCode());returnresult;}@Overridepublicbooleanequals(Objectobj){if(this==obj)returntrue;if(obj==null)returnfalse;if(getClass()!=obj.getClass())returnfalse;Personother=(Person)obj;if(age!=other.age)returnfalse;if(name==null){if(other.name!=null)returnfalse;}elseif(!name.equals(other.name))returnfalse;returntrue;}@OverridepublicStringtoString(){return"Person[name="+name+",age="+age+"]";}//getter&setterpublicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}}publicstaticvoidmain(String[]args){//利用HashSet來存取自定義對象PersonSet<Person>set=newHashSet<Person>();set.add(newPerson("張三",12));set.add(newPerson("李四",13));set.add(newPerson("王五",22));set.add(newPerson("張三",12));//遍歷for(Personp:set){System.out.println(p);}//結果:向集合中存儲兩個張三對象,但是集合中就成功存儲了壹個/*Person[name=王五,age=22]Person[name=李四,age=13]Person[name=張三,age=12]*/}所以在向HashSet集合中存儲自定義對象時,為了保證set集合的唯壹性,那麽必須重寫hashCode和equals方法。
LinkedHashSet:是基於鏈表和哈希表***同實現的,所以具有存取有序,元素唯壹
publicstaticvoidmain(String[]args){//利用LinkedHashSet來存取自定義對象PersonLinkedHashSet<Person>set=newLinkedHashSet<Person>();set.add(newPerson("張三",12));set.add(newPerson("李四",13));set.add(newPerson("王五",22));set.add(newPerson("張三",12));//遍歷for(Personp:set){System.out.println(p);}//結果:向集合中存儲兩個張三對象,但是集合中就成功存儲了壹個,//並且存進的順序,和取出來的順序是壹致的/*Person[name=張三,age=12]Person[name=李四,age=13]Person[name=王五,age=22]*/}TreeSet:TreeSet是SortedSet接口的實現類
TreeSet特點:存取無序,元素唯壹,可以進行排序(排序是在添加的時候進行排序)
TreeSet支持兩種排序方法:自然排序和定制排序。默認情況下,TreeSet采用自然排序
TreeSet集合存儲String對象
publicstaticvoidmain(String[]args){TreeSet<String>treeSet=newTreeSet<String>();treeSet.add("a");treeSet.add("c");treeSet.add("d");treeSet.add("b");for(Stringstr:treeSet){System.out.println(str);}//結果:取出來的結果是經過排序的/*abcd*/}TreeSet保證元素的唯壹性是有兩種方式:
1、自定義對象實現Comparable接口,重寫comparaTo方法,該方法返回0表示相等,小於0表示準備存入的元素比被比較的元素小,否則大於0;
2、在創建TreeSet的時候向構造器中傳入比較器Comparator接口實現類對象,實現Comparator接口重寫compara方法。
如果向TreeSet存入自定義對象時,自定義類沒有實現Comparable接口,或者沒有傳入Comparator比較器時,會出現ClassCastException異常。
下面就是演示用兩種方式來存儲自定義對象
packageorg.example.test;importjava.util.LinkedList;/***利用LinkedList來模擬棧*棧的特點:先進後出*/publicclassTest12{privateLinkedList<String>linkList=newLinkedList<String>();//壓棧publicvoidpush(Stringstr){linkList.addFirst(str);}//出棧publicStringpop(){returnlinkList.removeFirst();}//查看publicStringpeek(){returnlinkList.peek();}//判斷是否為空publicbooleanisEmpty(){returnlinkList.isEmpty();}}classTest13{publicstaticvoidmain(String[]args){//測試棧Test12test12=newTest12();test12.push("我是第1個進去的");test12.push("我是第2個進去的");test12.push("我是第3個進去的");test12.push("我是第4個進去的");test12.push("我是第5個進去的");//取出while(!test12.isEmpty()){Stringpop=test12.pop();System.out.println(pop);}//打印結果/*我是第5個進去的我是第4個進去的我是第3個進去的我是第2個進去的我是第1個進去的*/}}0另壹種方式:使用比較器Comparator
packageorg.example.test;importjava.util.LinkedList;/***利用LinkedList來模擬棧*棧的特點:先進後出*/publicclassTest12{privateLinkedList<String>linkList=newLinkedList<String>();//壓棧publicvoidpush(Stringstr){linkList.addFirst(str);}//出棧publicStringpop(){returnlinkList.removeFirst();}//查看publicStringpeek(){returnlinkList.peek();}//判斷是否為空publicbooleanisEmpty(){returnlinkList.isEmpty();}}classTest13{publicstaticvoidmain(String[]args){//測試棧Test12test12=newTest12();test12.push("我是第1個進去的");test12.push("我是第2個進去的");test12.push("我是第3個進去的");test12.push("我是第4個進去的");test12.push("我是第5個進去的");//取出while(!test12.isEmpty()){Stringpop=test12.pop();System.out.println(pop);}//打印結果/*我是第5個進去的我是第4個進去的我是第3個進去的我是第2個進去的我是第1個進去的*/}}1三、Map集合map集合下面有HashMap,LinkedHashMap和TreeMap
Map用於保存兩組具有映射關系的數據,壹組值用於保存Map裏的Key,另外壹組用於保存Map裏的Value
Map中的key和value都可以是任何引用類型的數據
Map中的Key不允許重復,即同壹個Map對象的任何兩個Key通過equals方法比較中返回false
Key和Value之間存在單向壹對壹關系,即通過指定的Key總能找到唯壹的,確定的Value。
HashMap:是基於哈希表結構實現的,所以存儲自定義對象作為鍵時,必須重寫hasCode和equals方法,存取無序的。
下面演示HashMap以自定義對象作為鍵:
packageorg.example.test;importjava.util.LinkedList;/***利用LinkedList來模擬棧*棧的特點:先進後出*/publicclassTest12{privateLinkedList<String>linkList=newLinkedList<String>();//壓棧publicvoidpush(Stringstr){linkList.addFirst(str);}//出棧publicStringpop(){returnlinkList.removeFirst();}//查看publicStringpeek(){returnlinkList.peek();}//判斷是否為空publicbooleanisEmpty(){returnlinkList.isEmpty();}}classTest13{publicstaticvoidmain(String[]args){//測試棧Test12test12=newTest12()