Java-Map(容器)

为什么要有map?

HashSet没有索引,不能通过索引进行操作,可以把map当成自定义索引的HashSet。

 

Map是以键-值对保存数据的,其中值就是我们真实保存的值,键是我们自定义的索引。

 

Map迭代的两种方式

1.map的keySet方法可以把当前map中所有的key封装到一个Set类型的容器中,对Set进行迭代即可。

 1 import java.util.*;
 2 
 3 public class Test1 {
 4     public static void main(String args[]) throws Exception{
 5         Map<Integer,String> map = new HashMap<Integer,String>();
 6         map.put(0,"h");
 7         map.put(1,"e");
 8         map.put(2,"l");
 9         map.put(3,"l");
10         map.put(4,"o");    
11         
12         Set<Integer> keys= map.keySet();
13         Iterator<Integer> i = keys.iterator();
14         
15         while(i.hasNext()){
16             int key = i.next();
17             System.out.println("key:"+ key +"   value:"+ map.get(key));
18         }
19     }
20 }

 

2.用map中的entrySet把map中的所有entry封装到一个Set类型的容器中。

Entry

把Map看成是HashSet,那么这个HashSet中放的都是Entry,每一对key-value都是Entry的一部分。

import java.util.*;

public class Test1 {
    public static void main(String args[]) throws Exception{
        Map<Integer,String> map = new HashMap<Integer,String>();
        map.put(0,"h");
        map.put(1,"e");
        map.put(2,"l");
        map.put(3,"l");
        map.put(4,"o");    
        
        Set<Map.Entry<Integer,String>> s = map.entrySet();
        Iterator<Map.Entry<Integer,String>> i = s.iterator();
        
        while(i.hasNext()){
            Map.Entry<Integer,String> entry = i.next();
            System.out.println("key:"+ entry.getKey() +"   value:"+ entry.getValue());
        }
    }
}

 

 

posted @ 2013-11-03 13:07  _Su  阅读(1172)  评论(0)    收藏  举报