復習java基礎第四天(集合:List、Map、Collections、Enumeration)


一、List:

List 代表一個元素有序、且可重復的集合,集合中的每個元素都有其對應的順序索引

List 允許使用重復元素,可以通過索引來訪問指定位置的集合元素

List 默認按元素的添加順序設置元素的索引

List 集合里添加了一些根據索引來操作集合元素的方法

另外:

List 額外提供了一個 listIterator() 方法,該方法返回一個 ListIterator 對象,

ListIterator 接口繼承了 Iterator 接口,提供了專門操作 List 的方法

boolean hasPrevious()
Object previous()
void add()

ArrayList 和 Vector 是 List 接口的兩個典型實現 區別:

1、Vector 是一個古老的集合,通常建議使用 ArrayList。

2、ArrayList 是線程不安全的,而 Vector 是線程安全的。

3、即使為保證 List 集合線程安全,也不推薦使用 Vector

 1 public class Person {
 2     
 3      private String name;
 4      private int age;
 5      
 6     public String getName() {
 7         return name;
 8     }
 9     public void setName(String name) {
10         this.name = name;
11     }
12     public int getAge() {
13         return age;
14     }
15     public void setAge(int age) {
16         this.age = age;
17     }
18     public Person(String name, int age) {
19         super();
20         this.name = name;
21         this.age = age;
22     }
23     public Person(){}
24     @Override
25     public String toString() {
26         return "Person [name=" + name + ", age=" + age + "]";
27     }  
28 }
練習代碼1:Person類
 1 import java.util.ArrayList;
 2 import java.util.Comparator;
 3 import java.util.List;
 4 
 5 public class TestArrayList {
 6     public static void main(String []args){
 7         
 8         List list = new ArrayList();
 9         List list2 = new ArrayList();
10         Person p1 = new Person("lisi007",15);
11         list.add(new Person("lisi003",12));
12         list.add(new Person("lisi003",12));
13         list.add(p1);
14         list.add(new Person("lisi005",10));
15         list.add(new Person("lisi006",20));
16         
17         for(Object obj:list){
18             System.out.println(obj);
19         }
20         
21         System.out.println();
22         list2.add(new Person("zhangsan",22));
23         list2.add(new Person("zhangsan",23));
24         list.addAll(2, list2);
25         list.add(3, p1);
26     //    list.remove(1);
27         
28         System.out.println(list.indexOf(p1));
29         System.out.println(list.lastIndexOf(p1));
30         
31         for(Object obj:list){
32             System.out.println(obj);
33         }
34                 
35 /*        //遍歷List方法1:調用iterator()方法
36         Iterator iterator = list.iterator();
37         while(iterator.hasNext()){
38             System.out.println(iterator.next());
39         }
40         
41         //遍歷List方法2:增強for循環
42         for(Object obj:list){
43             System.out.println(obj);
44         }
45         
46         //遍歷List方法3:for循環,利用get(int index)
47         for(int i=0;i<list.size();i++){
48             System.out.println(list.get(i));
49         }
50         //遍歷List方法4:
51         ListIterator li = list.listIterator();
52         while(li.hasNext()){
53             System.out.println(li.next());
54         }
55 */                
56     }     
57 }
練習代碼2:TestArrayList類(主程序)

 

二、Map:

——Map 用於保存具有映射關系的數據,因此 Map 集合里保存着兩組值, 一組值用於保存 Map 里的 Key,

      另外一組用於保存 Map 里的 Value

——Map 中的 key 和 value 都可以是任何引用類型的數據

——Map 中的 Key 不允許重復(值可以),即同一個 Map 對象的任何兩個 Key 通過 equals 方法比較中

      返回 false。

——Key 和 Value 之間存在單向一對一關系,即通過指定的 Key 總能找到唯一的,確定的 Value

Map常用方法

HashMap 和 Hashtable 是 Map 接口的兩個典型實現類,它們的區別:

——Hashtable 是一個古老的 Map 實現類,不建議使用。

——Hashtable 是一個線程安全的 Map 實現,但 HashMap 是線程不安全的。

——Hashtable 不允許使用 null 作為 key 和 value,而 HashMap 可以

注意

1、與 HashSet 集合不能保證元素的順序的順序一樣,Hashtable 、HashMap 也不能保證其中

     key-value 對的順序。

2、Hashtable 、HashMap 判斷兩個 Key 相等的標准是:兩個 Key 通過 equals 方法返回 true,

     hashCode 值也相等。

3、Hashtable 、HashMap 判斷兩個 Value相等的標准是:兩個 Value 通過 equals 方法返回 true。

另外:

——LinkedHashMap 是 HashMap 的子類。

——LinkedHashMap 可以維護 Map 的迭代順序:迭代順序與 Key-Value 對的插入順序一致。

Properties :

——Properties 類是 Hashtable 的子類,該對象用於處理屬性文件。

——由於屬性文件里的 key、value 都是字符串類型,所以 properties 里的 Key 和 Value 都是字符串類型的。

TreeMap

1、TreeMap 存儲 Key-Value 對時,需要根據 Key 對 key-value 對進行排序。

     TreeMap 可以保證所有的 Key-Value 對處於有序狀態。

2、TreeMap 的 Key 的排序:

——自然排序:TreeMap 的所有的 Key 必須實現 Comparable 接口,而且所有的 Key 應該是

      同一個類的對象,否則將會拋出 ClasssCastException。

——定制排序:創建 TreeMap 時,傳入一個 Comparator 對象,該對象負責對 TreeMap 中的

      所有 key 進行排序。此時不需要 Map 的 Key 實現 Comparable 接口

練習代碼:

1 url=jdbc:mysql:///test
2 driver=com.mysql.jdbc.Driver
3 user=root
4 password=123
jdbc.properties
 1 public class Person {
 2     
 3      private String name;
 4      private int age;
 5      
 6     public String getName() {
 7         return name;
 8     }
 9     public void setName(String name) {
10         this.name = name;
11     }
12     public int getAge() {
13         return age;
14     }
15     public void setAge(int age) {
16         this.age = age;
17     }
18     public Person(String name, int age) {
19         super();
20         this.name = name;
21         this.age = age;
22     }
23     public Person(){}
24     @Override
25     public String toString() {
26         return "Person [name=" + name + ", age=" + age + "]";
27     }  
28 }
Person類
 1 import java.io.FileInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.IOException;
 4 import java.util.Collection;
 5 import java.util.Comparator;
 6 import java.util.HashMap;
 7 import java.util.Map;
 8 import java.util.Properties;
 9 import java.util.Set;
10 import java.util.TreeMap;
11 
12 public class TestHashMap {
13       public static void main(String []args) throws FileNotFoundException, IOException{
14           Map map = new HashMap();
15           
16           //添加Map元素:key不可以重復,value可以重復
17           map.put("AA", new Person("AAA",12));
18           map.put("DD", new Person("AA",12));
19           map.put("CC", new Person("CCC",13));
20           map.put("MM", new Person("MMM",15));
21           map.put("NN", new Person("AA",14));
22           
23           //遍歷Map中的元素:得到鍵的集合通過keySet()方法
24           Set keySet = map.keySet();
25           for(Object obj:keySet){
26               Object value = map.get(obj);
27               System.out.println("key= "+obj+"  value= "+value);
28           }
29           
30           //直接得到值的集合
31           Collection values = map.values(); //這里得到的值是可以重復的
32           for(Object val:values){
33               System.out.println(val);
34           }
35           
36           //得到鍵值對的集合
37 /*        Map<String,Object> map = new HashMap<String,Object>();//此方法需要泛型
38           for(Map.Entry<String, Object> kv:map.entrySet()){
39               String key = kv.getKey();
40               Object value = kv.getValue();
41               System.out.println(key + " : " +value);
42           }*/
43           
44           //移除元素的
45           map.remove("DD");
46           
47           //操作Map的工具方法:
48           System.out.println(map.size());
49           System.out.println(map.isEmpty());
50           System.out.println(map.containsKey("AA"));
51           
52           Comparator comparator = new Comparator(){
53             @Override
54             public int compare(Object o1, Object o2) {
55                 int result;
56                  Person p1 = (Person) o1;
57                  Person p2 = (Person) o2;
58                  result = p1.getAge() - p2.getAge();
59                 if(result == 0){
60                     return p1.getName().compareTo(p2.getName());
61                 }
62                 return result;
63             }
64           };
65           
66           TreeMap tm = new TreeMap(comparator);
67           tm.put(new Person("ABC",12), "ABC");
68           tm.put(new Person("ABCDF",17), "ABCD");
69           tm.put(new Person("ABCDE",14), "ABCD");
70           tm.put(new Person("ABCD",14), "ABCD");
71           
72           Set c = tm.keySet();
73           for(Object keys:c){
74               Object value = tm.get(keys);
75               System.out.println(keys+"  :  "+value);
76           }
77           
78           //properties文件在java中對應的是一個properties類的對象
79           //1、創建一個properties類的對象
80            Properties properties = new Properties();
81            
82           //2、使用IO流加載對應的properties文件
83            properties.load(new FileInputStream("jdbc.properties"));
84            
85           //3、得到對應的屬性值
86           String url = properties.getProperty("url");
87           System.out.println(url);              
88       }
89 }
TestHashMap類(主程序)

 

三、操作集合的工具類:Collections:(注意不是Collection)

1、Collections 是一個操作 Set、List 和 Map 等集合的工具類

2、Collections 中提供了大量方法對集合元素進行排序、查詢和修改等操作,還提供了對集合對象設置不可變、

     對集合對象實現同步控制等方法。

排序操作:

reverse(List):反轉 List 中元素的順序。

shuffle(List):對 List 集合元素進行隨機排序。

sort(List):根據元素的自然順序對指定 List 集合元素按升序排序。

sort(List,Comparator):根據指定的 Comparator 產生的順序對 List 集合元素進行排序。

swap(List,int, int):將指定 list 集合中的 i 處元素和 j 處元素進行交換。

同步控制

Collections 類中提供了多個 synchronizedXxx() 方法,該方法可使將指定集合包裝成線程同步的集合,

從而可以解決多線程並發訪問集合時的線程安全問題。

 

四、Enumeration

Enumeration 接口是 Iterator 迭代器的 “古老版本”

練習代碼:

 1 public class Person {
 2     
 3      private String name;
 4      private int age;
 5      
 6     public String getName() {
 7         return name;
 8     }
 9     public void setName(String name) {
10         this.name = name;
11     }
12     public int getAge() {
13         return age;
14     }
15     public void setAge(int age) {
16         this.age = age;
17     }
18     public Person(String name, int age) {
19         super();
20         this.name = name;
21         this.age = age;
22     }
23     public Person(){}
24     @Override
25     public String toString() {
26         return "Person [name=" + name + ", age=" + age + "]";
27     }  
28 }
Person類
 1 import java.util.ArrayList;
 2 import java.util.Collections;
 3 import java.util.Comparator;
 4 import java.util.Enumeration;
 5 import java.util.List;
 6 
 7 public class TestCollections {
 8     public static void main(String []args){
 9         
10      List list = new ArrayList();
11      list.add(new Person("lisi003",22));
12      list.add(new Person("lisi009",18));
13      list.add(new Person("lisi005",20));
14      list.add(new Person("lisi001",12));
15      
16      //使用Collection中的方法對list中和元素進行排序
17      Collections.sort( list, new Comparator() {
18         @Override
19         public int compare(Object o1, Object o2) {
20             Person p1 = (Person) o1;
21             Person p2 = (Person) o2;
22             return p1.getAge() - p2.getAge();
23         }
24     });
25      
26      for(Object obj:list){
27          System.out.println(obj);
28      }
29      
30      //獲取線程安全的list對象
31      List list2 = Collections.synchronizedList(new ArrayList());
32      
33      //對Enumeration進行遍歷
34      Enumeration names = Collections.enumeration(list);
35      while(names.hasMoreElements()){
36          System.out.println(names.nextElement());
37      }
38   }   
39 }
TestCollections類

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM