介绍一下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”));
}
}
运行后的输出如下:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值