雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java中map,set的简单使用

Posted on 2014-09-16 10:55  huhuuu  阅读(9276)  评论(0编辑  收藏  举报
package test2;

import  java.util.*;
import static java.lang.System.out;

public class test2 extends StaticSuper{
    
    //put输入,get,得到
    static void mapTest(){
        // TODO 自动生成的方法存根
        HashMap<String, String> map = new HashMap<String, String>();
        
        map.put("1", "a1");
        map.put("2", "a2");
        map.put("3", "a3");
        
        
        //遍历的方法一、缺点,费时
        Iterator<String> iterator = map.keySet().iterator() ;
        while (iterator.hasNext()){
            //Object key = iterator; 
            Object key = iterator.next(); 
            System.out.print("Key = " + key);
            System.out.println(", Value = "+map.get(key));
            //iterator.next();
        }
        
        //遍历的方法二,省时
        Iterator entries = map.entrySet().iterator();  
        while(entries.hasNext()){
            Map.Entry entry = (Map.Entry) entries.next();  
            Object key =  entry.getKey();  
            Object value = entry.getValue();  
            System.out.println("Key = " + key + ", Value = " + value);  
        }
        
        System.out.println("map end!");
    }
    
    static void setTest(){
        Set<String> set1 = new HashSet<String>();
        set1.add("s1_1");
        set1.add("s1_2");
        set1.add("s1_3");
        set1.add("one");
        
        System.out.println(set1);
        
        Set<String> set2 = new HashSet<String>();
        set2.add("s2_1");
        set2.add("s2_1");
        set2.add("s2_3");
        set2.add("one");
        
        System.out.println(set2);
        
        Set<String> sn = new HashSet<String>(set1);
        sn.retainAll(set2);
        System.out.println(sn);
    }
    

    public static void main(String[] args) {
        
    }

}