介绍一下Java的Map以及如何使用HashMap

开心编程网   2010年02月23日 20:44   评论»  

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”));

}
}

运行后的输出如下:

Rohit : 3434.34
Ashish : 1200.34
Pankaj : -19.34
Mohit : 123.22
Khariwal : 99.34
Rohit new balance : 4434.34

欢迎您发表评论:

赞助商链接

最新新闻动态

友情链接

关于站点 - 联系我们 - 网站大事 - 友情链接 - 免责声明 - 意见反馈 - 网站投稿 - 站点地图
版权所有开心编程网禁止转载! Copyright © 2009-2010 All Rights Reserved. Email:hbhgfzk@126.com