Java 简明教程
Java HashMap Class
Introduction
Java HashMap 类是 Map
接口的基于哈希表实现,以下是有关 HashMap
的一些要点:
The Java HashMap class is the Hash table based implementation of the Map interface.Following are the important points about HashMap −
-
This class makes no guarantees as to the iteration order of the map; in particular, it does not guarantee that the order will remain constant over time.
-
This class permits null values and the null key.
Class declaration
以下是 java.util.HashMap 类的声明:
Following is the declaration for java.util.HashMap class −
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
Parameters
以下是 java.util.HashMap 类的参数:
Following is the parameter for java.util.HashMap class −
-
K − This is the type of keys maintained by this map.
-
V − This is the type of mapped values.
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.AbstractMap
-
java.util.Object
-
java.util.Map
Example
以下程序说明了 HashMap 集合支持的几种方法 -
The following program illustrates several of the methods supported by HashMap collection −
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));
}
}
这会产生以下结果 −
This will produce the following result −