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