List和Map集合詳細分析

1.Java集合主要三種類型(兩部分):

第一部分:Collection(存單個數據,只能存取引用類型)html

  (1).List :是一個有序集合,能夠放重複的數據;(存順序和取順序相同)java

  (2).Set :是一個無序集合,不容許放置重複的數據;(存順序和取順序不必定相同)數組

  (3).SortedSet:無序不可重複,存進去的元素能夠按照元素的大小自動排序。安全

第二部分:Map(存成對數據)微信

  (1).Map: 是一個無序集合,集合中包含一個鍵對象,一個值對象,鍵對象不容許重複,值對象能夠重複(身份證號-姓名)。數據結構

2.Java集合存取數據類型及結構

2.1  常見集合的繼承結構-Collection

   

                                          

2.1.一、集合中經常使用實現類的數據結構分析:dom

(1)List集合ide

  List集合繼承了Collection接口,所以包含了collection中全部的方法,此外,List接口還定義瞭如下兩個很是重要的方法:工具

  (a)get(int index):得到指定索引位置的元素學習

  (b)set(int index,Object obj):將集合中指定索引位置的對象修改成指定對象。

(2)ArrayList

  採用數組存儲元素,適合查詢,不適合隨機增刪元素。(經常使用)。是可變數組,容許保存全部的元素,包括null,並能夠根據索引位置對集合進行快速的隨機訪問:缺點是指定的索引位置插入對象或刪除對象的速度較慢。

(3)LinkedList

  底層採用雙向鏈表數據結構存儲數據,適合頻繁的增刪元素,不適合查詢元素。

(4)Vector

  底層和ArrayList集合相同,可是 Vector是線程安全的,效率較低。(不經常使用)

(5)Set集合

   Set集合中的元素不按特定的方式排序,只是簡單地把對象加入集合,Set集合中不能包含重複對象。set集合有Set接口的實現類組成,set接口繼承了Collection接口,因包含了Collction接口的全部方法。 Set的構造方法有一個約束條件,傳入的Collection對象不能把有重複值,必須當心操做可變對象(Mutable Object)。若是一個Set中可變元素改變了自身狀態致使Object。equals(Object) = true,則會出現一些問題。

(6)HashSet

  哈希表/散列表,底層是一個HashMap。HashSet有如下特色:

  a. 不能保證元素的排列順序,順序有可能發生變化
  b.不是同步的
  c. 集合元素能夠是null,但只能放入一個null

  當向HashSet結合中存入一個元素時,HashSet會調用該對象的hashCode()方法來獲得該對象的hashCode值,而後根據 hashCode值來決定該對象在HashSet中存儲位置。

       簡單的說,HashSet集合判斷兩個元素相等的標準是兩個對象經過equals方法比較相等,而且兩個對象的hashCode()方法返回值相 等。
  注意,若是要把一個對象放入HashSet中,重寫該對象對應類的equals方法,也應該重寫其hashCode()方法。

  其規則是若是兩個對 象經過equals方法比較返回true時,其hashCode也應該相同。另外,對象中用做equals比較標準的屬性,都應該用來計算 hashCode的值。

(5)TreeSet:

  TreeSet是SortedSet接口的惟一實現類,TreeSet能夠確保集合元素處於排序狀態。TreeSet支持兩種排序方式, 天然排序定製排序,其中天然排序爲默認的排序方式。向TreeSet中加入的應該是同一個類的對象。

  天然排序使用要排序元素的CompareTo(Object obj)方法來比較元素之間大小關係,而後將元素按照升序排列。
  Java提供了一個Comparable接口,該接口裏定義了一個compareTo(Object obj)方法,該方法返回一個整數值,實現了該接口的對象就能夠比較大小。
   obj1.compareTo(obj2)方法若是返回0,則說明被比較的兩個對象相等,若是返回一個正數,則代表obj1大於obj2,若是是 負數,則代表obj1小於obj2。  
  若是咱們將兩個對象的equals方法老是返回true,則這兩個對象的compareTo方法返回應該返回0    
b.定製排序
  定製排序是根據集合元素的大小,以升序排列,若是要定製排序,應該使用Comparator接口,實現 int compare(T o1,T o2)方法

2.1.二、Collection接口中的方法分析:

(1).list集合

 1 package list;
 2 import java.util.*;
 3 import java.util.ArrayList;
 4 public class Gather { // 建立類Gather
 5     public static void main(String[] args) { // 主方法
 6       List<String> list = new ArrayList<>();//建立集合對象
 7       list.add("a");
 8       list.add("b");
 9       list.add("c");
10       //得到0~2之間隨機數
11       int i = (int)(Math.random()*(list.size() - 1));
12       System.out.println("隨機數組中的元素: "+list.get(i));
13       list.remove(2);//將指定索引位置的元素從集合中移除
14       System.out.println("將索引是2的元素從數組中移除後數組中的元素是:");
15       for(int j = 0;j < list.size();j++){//循環遍歷結合
16           System.out.println(list.get(j));
17       }
18    }
19     
20 }
21 /*
22 運行結果:
23 
24 隨機數組中的元素: a
25 將索引是2的元素從數組中移除後數組中的元素是:
26 a
27 b
28 */
View Code

(2)set集合

 1 import java.util.*;
 2 /**
 3  * 在項目中建立類UpdateStu,實現Comparable接口,重寫該接口中的compareTo()方法。在主方法中
 4  * 建立UpdateStu對象,建立集合,並將UpdataStu對象添加到集合中,遍歷該集合中的所有元素,以及經過
 5  * headSet(),subSet()方法得到的所有的部分集合。
 6  * @author z
 7  *
 8  */
 9 public class UpdateStu implements Comparable<Object> {
10     String name;
11     long id;
12     public UpdateStu(String name, long id) {
13         this.id = id;
14         this.name = name;
15     }
16     public int compareTo(Object o) {
17         UpdateStu upstu = (UpdateStu) o;
18         int result = id > upstu.id ? 1 : (id == upstu.id ? 0 : -1);
19         return result;
20     }
21     public long getId() {
22         return id;
23     }
24     public void setId(long id) {
25         this.id = id;
26     }
27     public String getName() {
28         return name;
29     }
30     public void setName(String name) {
31         this.name = name;
32     }
33     public static void main(String[] args) {
34         UpdateStu stu1 = new UpdateStu("李同窗", 01011);
35         UpdateStu stu2 = new UpdateStu("陳同窗", 01021);
36         UpdateStu stu3 = new UpdateStu("王同窗", 01051);
37         UpdateStu stu4 = new UpdateStu("馬同窗", 01012);
38         TreeSet<UpdateStu> tree = new TreeSet<>();
39         tree.add(stu1);
40         tree.add(stu2);
41         tree.add(stu3);
42         tree.add(stu4);
43         Iterator<UpdateStu> it = tree.iterator();
44         System.out.println("Set集合中的全部元素:");
45         while (it.hasNext()) {
46             UpdateStu stu = (UpdateStu) it.next();
47             System.out.println(stu.getId() + " " + stu.getName());
48         }
49         it = tree.headSet(stu2).iterator();
50         System.out.println("截取前面部分的集合:");
51         while (it.hasNext()) {
52             UpdateStu stu = (UpdateStu) it.next();
53             System.out.println(stu.getId() + " " + stu.getName());
54         }
55         it = tree.subSet(stu2, stu3).iterator();
56         System.out.println("截取中間部分的集合");
57         while (it.hasNext()) {
58             UpdateStu stu = (UpdateStu) it.next();
59             System.out.println(stu.getId() + " " + stu.getName());
60         }
61     }
62 }
63 /*
64 運行結果:
65 
66   
67 
68 Set集合中的全部元素:
69 521 李同窗
70 522 馬同窗
71 529 陳同窗
72 553 王同窗
73 截取前面部分的集合:
74 521 李同窗
75 522 馬同窗
76 截取中間部分的集合
77 529 陳同窗
78 
79    分析:存入TreeSet類實現的Set集合必須實現Comparable接口,該接口中的compareTo(Object o)方法比較此對象與指定對象的順序,若是該對象小於,等於,或大於指定對象,則分別返回負整數,0或正整數。
80 */
View Code

(3)contains方法:boolean contains(object o);判斷集合中是否包含某個元素

 1 import java.util.*;
 2 
 3 class  Collection01
 4 {
 5     //重寫equals方法
 6     
 7     public static void main(String[] args) 
 8     {
 9         //建立集合
10         Collection c = new ArrayList();
11         //建立Integer類型對象
12         Integer i1 = new Integer(10);
13         //添加元素
14         c.add(i1);
15         //判斷集合中是否包含i1
16         System.out.println(c.contains(i1));//true
17         
18         Integer i2= new Integer(10);
19         System.out.println(c.contains(i2));//true
20         
21         Manager m1=new Manager(100,"JACK");
22         c.add(m1);
23         //contasins方法調用底層的是equals方法,若是equals方法返回True,就是包含
24         System.out.println(c.contains(m1));//true
25         
26         Manager m2=new Manager(100,"JACK");
27         //重寫equas方法以前返回false,(比較內存地址)
28         //System.out.println(c.contains(m2));//false
29         //重寫equas方法以後返回True,集合中的對象都要重寫equalos方法(比較內容)
30         System.out.println(c.contains(m2));//true
31      
32     }
33 }
34 class Manager
35 { 
36    int no;
37    String name;
38    Manager(int no,String name)
39    {
40        this.no=no;
41        this.name=name;
42    }
43    public boolean equals(Object o)
44    {
45        if(this==o) return true;
46        if(o instanceof Manager)
47        {
48          Manager m = (Manager)o;
49          if(m.no == this.no && m.name.equals(this.name))
50            {
51              return true;
52            }
53        }
54        return false;
55    }
56 
57 }
View Code

(4)remove方法:boolean remove(object o);刪除集合中的某個元素

 1 import java.util.*;
 2 /*
 3   boolean remove(Object o)
 4   集合中的元素都須要重寫equals方法,在Object的equals方法比較內存地址,在解決實際問題的時候應該比較內容
 5 */
 6 
 7 class  Remove
 8 {
 9     public static void main(String[] args) 
10     {
11         Collection c = new ArrayList();
12         Integer i1 = new Integer(10);
13         c.add(i1);
14         Integer i2=new Integer(10);
15         c.remove(i2);
16         System.out.println(c.size());//0
17         Manager m2=new Manager(100,"ZHANG");
18         c.remove(m2);
19         System.out.println(c.size());//0
20     }
21 }
22 class Manager
23 { 
24    int no;
25    String name;
26    Manager(int no,String name)
27    {
28        this.no=no;
29        this.name=name;
30    }
31    
32 }
View Code

(5)兩種remove方法的區別

  a.迭代器的remove方法

 1 import java.util.*;
 2 
 3 class  Remove1
 4 {
 5     public static void main(String[] args) 
 6     {
 7         Collection c = new ArrayList();
 8         c.add(1);
 9         c.add(2);
10         c.add(3);
11         Iterator it = c.iterator();
12         while(it.hasNext())
13         {
14             Object element = it.next();
15             it.remove();
16         }
17         System.out.println(c.size());
18     }
19 }
View Code

  b.集合自身帶的remove方法

 1 import java.util.*;
 2 
 3 class  Remove1
 4 {
 5     public static void main(String[] args) 
 6     {
 7         Collection c = new ArrayList();
 8         c.add(1);
 9         c.add(2);
10         c.add(3);
11         Iterator it = c.iterator();
12         while(it.hasNext())
13         {
14             Object element = it.next();
15             c.remove(element);
16             //集合自身帶的remove在將元素刪除後,迭代器失效,須要從新得到迭代器,若不添加此語句,則會出現異常
17             it = c.iterator();
18         }
19         System.out.println(c.size());
20     }
21 }
View Code

2.1.三、List接口中的方法分析:(有序可重複)

(1).添加元素,遍歷元素

 1 import java.util.*;
 2 
 3 class Main   //有序可重複
 4 {
 5     public static void main(String[] args) 
 6     {
 7         List L = new ArrayList();
 8         L.add(100);
 9         L.add(200);
10         L.add(1300);
11         L.add(120);
12         L.add(100);
13         Iterator it = L.iterator();
14         while (it.hasNext())
15         {
16            Object element =  it.next();
17            System.out.println(element);
18         }
19         
20     }
21 }
View Code

(2)ArrayList底層原理

 1 package shili;
 2 
 3 import java.util.*;
 4 /**
 5  * ArrayList底層集合是數組
 6  * ArrayList默認容量是10,擴容後的新容量是原容量的1.5倍
 7  * vector集合底層默認初始容量是10,擴容後是原容量的2倍。
 8  * 若是優化ArrayList和Vector?
 9  * 儘可能減小擴容操做,擴容須要拷貝數組,拷貝很消耗內存,通常在建立集合時指定初始化
10 */
11 class Main
12 {
13     public static void main(String[] args) 
14     {
15         //建立List集合
16         List l = new ArrayList();
17         l.add(10);
18         l.add(20);
19         l.add(30);
20         //在下標爲1的位置上添加100
21         l.add(1,100);
22         //獲取第一個元素
23         System.out.println(l.get(0));
24         //便利(List集合特有的便利方式)
25         System.out.println("--------------------");
26         for(int i=0;i<l.size();i++){
27             Object element= l.get(i);
28             System.out.println(element);
29         }
30         
31     }
32 }
View Code

(3)ArrayList與Vector的區別

  a.Vector是線程安全的,Arrayliast是線程不安全的 。

  b.ArrayList在底層數組不夠用的時候擴展爲原來的1.5倍,Vector默認擴展爲你原來的2倍。

  對於第一點能夠經過原碼來觀察:

  vector原碼:

 1 public class Vector<E>
 2     extends AbstractList<E>
 3     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
 4 {
 5     /**
 6      * The array buffer into which the components of the vector are
 7      * stored. The capacity of the vector is the length of this array buffer,
 8      * and is at least large enough to contain all the vector's elements.
 9      *
10      * <p>Any array elements following the last element in the Vector are null.
11      *
12      * @serial
13      */
14     protected Object[] elementData;
View Code

  Vector的add方法:

1 public synchronized boolean add(E e) {
2         modCount++;
3         ensureCapacityHelper(elementCount + 1);
4         elementData[elementCount++] = e;
5         return true;
6     }
View Code

  ArrayList的add方法

1  public boolean add(E e) {
2          ensureCapacityInternal(size + 1);  // Increments modCount!!
3          elementData[size++] = e;
4          return true;
5      }
View Code

  分析:從add方法中能夠看到,vector的add方法中添加了synchronized關鍵字來保證vector的線程是安全的。

其實vector的其餘方法中,也都加了synchronized關鍵字。

2.1.4  set接口中的方法分析:(無序不可重複)

(1).HasHset

                         

 1 /*
 2   set集合中存儲元素,該元素的hashCode和equals方法
 3   HashMap中有一個put的方法,put(key,value) key是無序不可重複的
 4   存儲在hashSet集合或者HashMap集合Key部分的元素,須要同時重寫hashCode方法和equals方法
 5 */
 6 import java.util.*;
 7 class  SetTest
 8 {
 9     public static void main(String[] args) 
10     {
11         //建立集合
12         Set es =new HashSet();
13         Employee e1 = new Employee("1000","u1");
14         Employee e2 = new Employee("1001","u2");
15         Employee e3 = new Employee("2000","u3");
16         Employee e4 = new Employee("2001","u4");
17         Employee e5 = new Employee("2001","u4");
18       
19        es.add(e1);
20        es.add(e2);
21        es.add(e3);
22        es.add(e4);
23        es.add(e5);
24       System.out.println(es.size());
25 
26     }
27 }
28 
29 //員工編號1000~9999
30 class Employee
31 {
32     String no;
33     String name;
34     Employee(String no,String name)
35     {
36         this.no=no;
37         this.name=name;
38     }
39     //重寫equals方法,若是員工編號相同,而且名字相同,則是同一個對象
40     public boolean equals(Object o)
41     {
42         if(this == o) {
43          return true;
44         }
45         if(o instanceof Employee){
46           Employee e= (Employee)o;
47           if(e.no.equals(this.no) && e.name.equals(this.name)){
48             return true;
49           }
50         }
51         return false;
52     }
53     //重寫hashCode方法
54     public int hashCode()
55     {
56         return no.hashCode();
57     }
58 
59 }
View Code

(2)SortedSet

 1 /*
 2   java.util.Set;
 3     java.util.SortSet;無序不可重複,可是進去的元素能夠按照元素的大小順序自動進行排序
 4       java.util.TreeSet;
 5 */
 6 import java.util.*;
 7 import java.text.*;
 8 class  SortSettest
 9 {
10     public static void main(String[] args) throws ParseException 
11     {
12         //建立集合
13         SortedSet ss = new TreeSet();
14         //天加元素 自動裝箱
15         ss.add(30);
16         ss.add(20);
17         ss.add(33);
18         ss.add(10);
19         ss.add(60);
20         ss.add(8);
21         //遍歷
22         Iterator it = ss.iterator();
23         while(it.hasNext()){
24            Object e = it.next();
25            System.out.println(e);
26         }
27         //String
28         SortedSet str = new TreeSet();
29         str.add("zhangsan");
30         str.add("lisi");
31         str.add("wangwu");
32         str.add("maliu");
33         str.add("liuba");
34         //遍歷
35         it = str.iterator();
36         while(it.hasNext()){
37            Object e = it.next();
38            System.out.println(e);
39         }
40         //Date
41      SortedSet times =  new TreeSet();
42         String t1 = "2009-10-01";
43         String t2 = "2012-01-01";
44         String t3 = "2014-06-08";
45         String t4 = "2018-07-01";
46         String t5 = "2008-08-08";
47         //設置格式
48       SimpleDateFormat def = new SimpleDateFormat("yyyy-MM-dd");
49         //日期格式化
50         Date ut1 = def.parse(t1);
51         Date ut2 = def.parse(t2);
52         Date ut3 = def.parse(t3);
53         Date ut4 = def.parse(t4);
54         Date ut5 = def.parse(t5);
55         //添加
56         times.add(ut1);
57         times.add(ut2);
58         times.add(ut3);
59         times.add(ut4);
60         times.add(ut5);
61         //遍歷
62 
63         it = times.iterator();
64         while(it.hasNext()){
65            Object e = it.next();
66            if(e instanceof Date){
67              Date d = (Date)e;
68              System.out.println(def.format(d));
69            }
70           
71         }
72 
73  
74     }
75 }
View Code

(3)SortedSet內部的比較方法compareTo()

 1 /*
 2    SortedSet集合存儲元素內部排序方法
 3    sun編寫TreeSe集合添加元素的時候,會調用compareTo方法完成比較
 4 */
 5 import  java.util.*;
 6 class  SortSet
 7 {
 8     public static void main(String[] args) 
 9     {
10         SortedSet users = new TreeSet();
11         User u1 = new User(10);
12         User u2 = new User(20);
13         User u3 = new User(13);
14         User u4 = new User(15);
15         User u5 = new User(2);
16         users.add(u1);
17         users.add(u2);
18         users.add(u3);
19         users.add(u4);
20         users.add(u5);
21         //遍歷
22         Iterator it = users.iterator();
23         while(it.hasNext())
24         {
25            System.out.println(it.next());
26         }
27     }
28 }
29 class User implements Comparable //必須實現comparable接口
30 {
31     int age;
32     User(int age)
33     {
34         this.age=age;
35     }
36     public String toString(){
37        return "User[age="+age+"]";
38     }
39     //實現java.lang.Comparable;接口中的comparable方法
40     //按照user的age進行排序
41     @Override
42     public int compareTo(Object o) {
43         // TODO 自動生成的方法存根
44         int age1=this.age;
45         int age2=((User)o).age;
46         return age2-age1;
47     }
48 }
View Code

(4)SortedSet內部的比較方法Comparator

 1 /*
 2 SortedSet集合存儲元素內部排序方法
 3 */
 4 import java.util.*;
 5 import java.util.Comparator;
 6 class Main 
 7 {
 8     public static void main(String[] args) 
 9     {
10         //建立TreeSet集合的時候提供一個比較器
11         SortedSet products = new TreeSet(new ProductComparator());
12         Product p1 = new Product(2.0);
13         Product p2 = new Product(3.0);
14         Product p3 = new Product(1.0);
15         Product p4 = new Product(6.0);
16         Product p5 = new Product(5.0);
17         //添加元素
18         products.add(p1);
19         products.add(p2);
20         products.add(p3);
21         products.add(p4);
22         products.add(p5);
23         //遍歷
24         Iterator it = products.iterator();
25         while(it.hasNext()){
26            System.out.println(it.next());
27         }
28     }
29 }
30 
31 
32 class Product 
33 {
34     double price;
35     Product(double price)
36     {
37         this.price=price;
38     }
39     public String toString(){
40       return price + "";
41     }
42 }
43 
44 
45 class ProductComparator implements Comparator
46 {
47     @Override
48     public int compare(Object o1, Object o2) {
49         // TODO 自動生成的方法存根
50         double price1 = ((Product)o1).price;
51         double price2 = ((Product)o2).price;
52         if(price1 == price2){
53          return 0;
54         }
55         else if(price1>price2){
56         return 1;
57         }
58         else{
59         return -1;
60         }
61     }
62 }
View Code

2.2  常見集合的繼承結構-Map

                                                                   

2.2.1 Map集合中經常使用實現類的數據結構及特色

  (1)HashMap :

  哈希表/散列表,底層是一個哈希表,HashMap中的Key等同一個Set集合(無序不重複,結構以下圖),容許key或vaue爲空,線程不安全。若是要使map線程安全,方法參考:http://www.cnblogs.com/cloudwind/archive/2012/08/30/2664003.html

 

                                                                                                    圖. 哈希表/散列表

(2)Hashtable

  線程安全的效率低。不容許key或vaue爲空,線程安全。

(3)Properties

   屬性類,也能夠是Key 和value的方式存儲元素,可是Key 和value只能是字符串類型。Properties是HashTable的子類,不過Properties添加了兩個方法,load()和store()能夠直接導入或者將映射寫入文件。

(4)SortedMap

  SortedMap中的key存儲元素的特色是:無序不可重複,但能夠按照元素的大小進行自動排序,SortedMap中的key等同於SortedSet。

(5)TreeMap

  TreeMap的Key就是一個TreeSet。

(6)LinkedHashMap

  詳解:http://www.cnblogs.com/chenpi/p/5294077.html 

2.2.二、 Map集合中經常使用的方法分析

                           

 1 /*
 2   Map中經常使用的方法舉例
 3   *存儲在Map集合key部分的元素須要重寫hashCode+equals方法
 4 */
 5 import java.util.*;
 6 class Maptest
 7 {
 8     public static void main(String[] args) 
 9     {
10         //建立Map集合
11         Map persons = new HashMap();//HashMap的默認初始化容量是16,默認加載因子是0.75
12         //存儲鍵值對
13         persons.put("10000","lisi");
14         persons.put("10001","張三");
15         persons.put("10002","wangwu");
16         persons.put("10003","maliu");
17         persons.put("10004","zhaoqi");
18         //判斷鍵值對你的個數,map中的key是無序不可重複的,和HashSet相同
19         System.out.println(persons.size());
20 
21         System.out.println(persons.containsKey("10000"));
22          
23         System.out.println(persons.containsValue("張三"));
24 
25         System.out.println(persons.get("10000"));
26  
27         persons.remove("10004");
28         System.out.println(persons.size());
29 
30         //獲取全部的value
31         Collection value = persons.values();
32         Iterator it = value.iterator();
33         while(it.hasNext())
34         {
35             System.out.println(it.next());
36         }
37         //獲取全部的Key
38         Set keys = persons.keySet();
39         Iterator it2 = keys.iterator();
40         while(it2.hasNext())
41         {
42             Object id = it2.next();
43             Object name = persons.get(id);
44             System.out.println(id+"->"+name);
45         }
46         //返回此映射中包含的映射關係的Set圖
47         Set entrySet = persons.entrySet();
48         Iterator it3 = entrySet.iterator();
49         while(it3.hasNext())
50         {
51             System.out.println(it3.next());
52         }
53         /*
54           輸出結果
55           10001=張三
56           10002=wangwu
57           10000=lisi
58           10003=maliu
59         */
60     }
61 }
View Code

(1)Hashtable集合中經常使用的方法分析

 1 /*
 2    HashMap默認初始化容量是16,默認加載因子是0.75
 3    Hashtable 默認初始化容量是11,默認家在因子是0.75
 4    java.util.Properties,是由key和value都是字符串類型
 5 */
 6 import java.util.Properties;
 7 class  MapProperties
 8 {
 9     public static void main(String[] args) 
10     {
11         //建立屬性類對象
12         Properties p = new Properties();
13         //存數據
14         p.setProperty("1000","z");
15         p.setProperty("1001","d");
16         p.setProperty("1002","s");
17         p.setProperty("1003","j");
18         //遍歷,經過key獲取value
19         String v1 = p.getProperty("1000");
20         String v2 = p.getProperty("1001");
21         String v3 = p.getProperty("1002");
22         String v4 = p.getProperty("1003");
23 
24         System.out.println(v1);
25         System.out.println(v2);
26         System.out.println(v3);
27         System.out.println(v4);
28     }
29 }
30 /*
31 運行結果 
32    z 
33    d
34    s
35    j
36 */
View Code

(2)SortedMap集合的用法

 

 1 import java.util.*;
 2 
 3 /*
 4 SortedMap中的key特色:無序不可重複,但存進去的元素能夠按照大小自動排序
 5 key的特色:1.實現Comparable接口2,,單獨寫一個比較器
 6 */
 7 class  SortedMaptest02
 8 {
 9     
10     public static void main(String[] args)
11     {
12         //Map,Key存儲Product,value個數
13         SortedMap<Product, Double> product = new TreeMap<Product, Double>();
14         //準備對象
15         Product p1 = new Product("肉1",12.0);
16         Product p2 = new Product("肉2",10.0);
17         Product p3 = new Product("肉3",11.0);
18         Product p4 = new Product("肉4",15.0);
19         Product p5 = new Product("肉5",17.0);
20         
21         product.put(p1,2.0);
22         product.put(p2,2.0);
23         product.put(p3,2.0);
24         product.put(p4,2.0);
25         product.put(p5,2.0);
26     //遍歷
27        Set keys = product.keySet();
28        Iterator it = keys.iterator();
29        while(it.hasNext())
30         {
31            Object k = it.next();
32            Object v = product.get(k);
33            System.out.println(k+"..."+v);
34         }
35     }
36 }
37 //實現Comparable接口
38 class Product implements Comparable
39 {
40      String name;
41      double price;
42      Product(String name,double price){
43     this.name = name;
44        this.price = price;
45      }
46      public String toString()
47     {
48          return "Product[name = "+name+",price = "+price+"]";
49     }
50     //實現compareo方法,按照商品價格進行排序
51     public int compareTo(Object o)
52     {
53         double price1 = this.price;
54         double price2 = ((Product)o).price;
55         if(price1>price2)
56             return 1;
57         else if(price2>price1)
58             return -1;
59         else return 0;
60 
61     }
62 }
View Code

2.3  Collections集合工具類的用法

 1 package test;
 2 
 3 /*
 4 1.集合工具類 java.util.Collections (類)
 5 2.Java.util.Collection 接口
 6 */
 7 import java.util.*;
 8 class Main 
 9 {
10     @SuppressWarnings("unchecked")
11     public static void main(String[] args) 
12     {
13         @SuppressWarnings("rawtypes")
14         List list = new ArrayList();
15         list.add("5");
16         list.add("9");
17         list.add("8");
18         list.add("4");
19         list.add("6");
20         @SuppressWarnings("rawtypes")
21         Iterator it = list.iterator();
22         while(it.hasNext()){
23           System.out.println(it.next());
24         }
25         System.out.println(".........................");
26         Collections.sort(list);
27         it = list.iterator();
28         while(it.hasNext()){
29           System.out.println(it.next());
30         }
31         
32         //對set集合進行排序
33         Set s =  new HashSet();
34         s.add("3");
35         s.add("1");
36         s.add("8");
37         s.add("4");
38         s.add("6");
39         System.out.println(".........................");
40         //不能更直接使用Collections。sort(s)進行排序
41         //將Set集合轉換成List集合
42         List lists = new ArrayList(s);
43         Collections.sort(lists);
44         it = lists.iterator();
45         while(it.hasNext()){
46           System.out.println(it.next());
47         }
48         //將ArrayList轉換成線程安全的
49         List mylist = new ArrayList<>();
50         Collections.synchronizedList(mylist);
51         
52     }
53 }
View Code

3.泛型

  泛型是Java SE 1.5的新特性,泛型的本質是參數化類型,也就是說所操做的數據類型被指定爲一個參數。這種參數類型能夠用在類、接口和方法的建立中,分別稱爲泛型類、泛型接口、泛型方法。 JAVA語言引入泛型的好處是安全簡單。在Java SE 1.5以前,沒有泛型的狀況的下,經過對類型Object的引用來實現參數的「任意化」,「任意化」帶來的缺點是要作顯式的強制類型轉換,而這種轉換是要求開發者對實際參數類型能夠預知的狀況下進行的。對於強制類型轉換錯誤的狀況,編譯器可能不提示錯誤,在運行的時候纔出現異常,這是一個安全隱患。

  泛型的好處是在編譯的時候檢查類型安全,而且全部的強制轉換都是自動和隱式的,以提升代碼的重用率
package test;

/*
JDk5.0新特性:泛型(編譯階段的語法,在編譯階段同一集合中的類型)
1.語法實現
2.優勢:使集合中的元素的類型統一,減小強制類型轉換
3.缺點:只能存儲一種數據類型
*/
import java.util.*;
class  Main
{
    public static void main(String[] args) 
    {
        //建立一個List集合,只能存儲字符串類型
        List <String> str = new ArrayList<String>();
        str.add("sd");
        str.add("sfhj");
        str.add("dsf");
        str.add("hjk");
        str.add("sdf");
        Iterator <String> it  = str.iterator();
        while(it.hasNext()){
            String s = it.next();
           System.out.println(s);
        }
    }
}
View Code

        歡迎掃碼關注個人微信公衆號,或者微信公衆號直接搜索Java傳奇,不定時更新一些學習筆記!

 
                                    
相關文章
相關標籤/搜索