java中HashMap类用法

 

/*
HashSet底层是采用HasMap实现的  HasMap保存的是  键值对
就跟 C++中 <map>容器类似
keySet() 返回键的视图  values() 返回值的视图

entrySet()  返回的每一个元素都是Map.Entry     Map中一个静态的接口接收键值对 
*/
import java.util.* ;
class  Test
{ private static HashMap<String,String> hm=new HashMap<String,String>() ;  //JDK1.5后引入范式概念
 public static void main(String []args)
 {
  hm.put("one","xiaoming") ;// 向其中添加键值对 因为没有实现Collection接口所以没有add方法
  hm.put("two","xiaozhang") ;
  hm.put("three","xiaoli") ;
  hm.put("four","xiaoliu") ;
  System.out.println(hm.get("one"));
  System.out.println(hm.get("two"));
    System.out.println(hm.get("three"));
    System.out.println(hm.get("four"));  
 
   
    Set s=hm.keySet() ;//返回键的视图 
    printElements(s);  //输出键列表
 
 
 
   
    Collection c=hm.values();
    printElements(c); //迭代器的好处是可以输出多种类型的数据    输出值列表
 
 
   
    Set ss=hm.entrySet() ;//返回Map.Entry 接口实现
    printElements(ss);   //输出键值对  利用迭代器 
   
  
  
  
    Iterator  i=ss.iterator() ;   //通过 Map.Entry静态接口 获取元素
    while(i.hasNext())
    {
     Map.Entry me=(Map.Entry)i.next() ;//强制转换
     System.out.println(me.getKey()+":"+me.getValue());
     
    }
   
   
   
   
  
 }
 
static public void printElements(Collection c)
 {
  Iterator i=c.iterator() ;
  while(i.hasNext())
  {
   System.out.println(i.next());
  }
  
  
 }
 
 
 
}

posted on 2011-08-09 15:49  风尘女子  阅读(14673)  评论(0编辑  收藏  举报

导航