HashMap用法 示例

来源:互联网 发布:java 解析word文档结构 编辑:程序博客网 时间:2024/04/19 18:52

转自

陈华江(HuaChiang Chen)专栏

/*

程序开始创建了一个散列映射,然后将名字的映射增加到平衡表。接下来,映射的内容通过使用由调用函数entrySet()而获得的集合“视图”而显示出来。关键字和值通过调用由Map.Entry定义的getKey()和getValue()方法而显示。注意存款是如何被制成Evan的账目的。put()方法自动用新值替换与指定关键字相关联的原先值。

*/

import java.util.*;
class HaspMapDemo{
 public static void main(String[] args)
 {
  //Create a hasp map
  HashMap   hm=new   HashMap();
  //Put elements to the map
  hm.put("Evan",new Double(12345.77));
  hm.put("Rose",new Double(78777));
  hm.put("Magic",new Double(-99.10));
  hm.put("Mike",new Double(100.00));
  hm.put("Sue",new Double(17.15));
  //Get a set of the entries
  Set set = hm.entrySet();
  //Get an iterator
  Iterator itr = set.iterator();
  //Display elements
  while (itr.hasNext()){
   Map.Entry me = (Map.Entry)itr.next();
   System.out.println(me.getKey() + ": ");
   System.out.println(me.getValue());
  }
  System.out.println();
  //Deposit 1000 into Evan's account
  double balance = ((Double)hm.get("Evan")).doubleValue();
  hm.put("Evan",new Double(balance + 1000));
  System.out.println("Evan's new balance : " + hm.get("Evan"));
 }
}

原创粉丝点击