HashMap类使用哈希表实现Map接口。这使得基本操作(例如get()和put())的执行时间即使对于大型集合也保持恒定。
以下是HashMap类支持的构造函数的列表。
序号 | 构造函数与说明 |
---|---|
1 | HashMap() 该构造函数构造一个默认的HashMap。 |
2 | HashMap(Map m) 此构造函数通过使用给定Map对象m的元素来初始化哈希映射。 |
3 | HashMap(int Capacity) 此构造函数将哈希映射的容量初始化为给定的整数值,容量。 |
4 | HashMap(int Capacity,float fillRatio) 此构造函数使用其参数初始化哈希映射的容量和填充率。 |
让我们看另一个例子-
import java.util.*; public class Main { public static void main(String args[]) { HashMap hashMap = new HashMap(); hashMap.put("John", new Integer(10000)); hashMap.put("Tim", new Integer(25000)); hashMap.put("Adam", new Integer(15000)); hashMap.put("Katie", new Integer(30000)); hashMap.put("Jacob", new Integer(45000)); hashMap.put("Steve", new Integer(23000)); hashMap.put("Nathan", new Integer(25000)); hashMap.put("Amy", new Integer(27000)); Set set = hashMap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry map = (Map.Entry)iterator.next(); System.out.print(map.getKey() + ": "); System.out.println(map.getValue()); } System.out.println(); System.out.println("Size of IdentintyHashMap: "+hashMap.size()); int bonus = ((Integer)hashMap.get("Amy")).intValue(); hashMap.put("Amy", new Integer(bonus + 5000)); System.out.println("Amy's salary after bonus = " + hashMap.get("Amy")); int deductions = ((Integer)hashMap.get("Steve")).intValue(); hashMap.put("Steve", new Integer(deductions - 3000)); System.out.println("Steve's salary after deductions = " + hashMap.get("Steve")); } }
输出结果
Adam: 15000 Nathan: 25000 Katie: 30000 Steve: 23000 John: 10000 Tim: 25000 Amy: 27000 Jacob: 45000 Size of IdentintyHashMap: 8 Amy's salary after bonus = 32000 Steve's salary after deductions = 20000