首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

介绍一上Java的Map以及怎么使用HashMap

2012-09-23 
介绍一下Java的Map以及如何使用HashMapMap是一个保存键值对的对象,根据键值可以找到它对应的值。键必须是唯

介绍一下Java的Map以及如何使用HashMap
Map是一个保存键值对的对象,根据键值可以找到它对应的值。键必须是唯一的,但是值可以重复。HashMap类提供了map接口的主要实现,它使用hash table来实现map接口。这就使得一些常见的操作如get()和put()所用的时间基本不变。
如下代码是一个使用hashmap的实例,它提供了account信息和account balance的对应:
import java.util.*;
public?class HashMapDemo {
public?static void main( String[] args)?{
HashMap?hm?= new HashMap();
hm.put(“Rohit”, new Double(3434.34));
hm.put(“Mohit”, new Double(123.22));
hm.put(“Ashish”, new Double(1200.34));
hm.put(“Khariwal”, new Double(99.34));
hm.put(“Pankaj”, new Double(-19.34));
Set?set?=?hm.entrySet();
Iterator?i?=?set.iterator();
while(i.hasNext()){
Map.Entry?me?= (Map.Entry)i.next();
System.out.println(me.getKey() + “?:?” +?me.getValue()?);
}
//deposit?into?Rohit's?Account
double balance?= ((Double)hm.get(“Rohit”)).doubleValue();
hm.put(“Rohit”, new Double(balance?+ 1000));
System.out.println(“Rohit?new?balance?:?” +?hm.get(“Rohit”));
}
}
运行后的输出如下:


热点排行