`

HashMap介绍不错的例子

    博客分类:
  • j2se
阅读更多
java 代码
  1. public class HashMapExample {   
  2.   
  3.  public static void main(String[] args) {   
  4.   
  5.   Map m1 = new HashMap();   
  6.   m1.put("Chinese"new Long(100000));   
  7.   m1.put("English"new Long(20000));   
  8.   m1.put("French"new Long(3000));   
  9.   m1.put("Korean"new Long(400));   
  10.   
  11.   System.out.println("The HashMap holds " + m1.size() + " elements");   
  12.   
  13.   System.out.println("The keys are:");   
  14.   
  15.   // 因为Map的key不可能重复,所以,可以用Set数据结构来存储   
  16.   //是这么考虑的啊,由于不能重复的原因啊,难怪不用List,它是可以重复的   
  17.   Set keySet = m1.keySet();   
  18.   Iterator ikey = keySet.iterator();   
  19.   while (ikey.hasNext()) {   
  20.    String s =(String) ikey.next();   
  21.       System.out.println("\t" + s +"==>"+m1.get(s));   
  22.   
  23.   }   
  24.   
  25.   System.out.println("The values are:");   
  26.   
  27.   // 因为Map的值有可能重复,所以不能用Set,要用Collection   
  28.   Collection valueCol = m1.values();   
  29.   Iterator ival = valueCol.iterator();   
  30.   while (ival.hasNext()) {   
  31.    System.out.println("\t" + ival.next());   
  32.   }   
  33.   
  34.   // 根据key,取出特定的值   
  35.   System.out.println("The value for Key \"Korean\" is "  
  36.     + m1.get("Korean").toString());   
  37.   }   
  38.   
  39. }   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics