1.构造函数
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). | ||||||||||||||||||||||||||
HashMap(int initialCapacity)
Constructs an empty
HashMap with the specified initial capacity and the default load factor (0.75).
| ||||||||||||||||||||||||||
HashMap(int initialCapacity, float loadFactor)
Constructs an empty
HashMap with the specified initial capacity and load factor.
| ||||||||||||||||||||||||||
HashMap(Map<? extends K,? extends V> m)
Constructs a new
HashMap with the same mappings as the specified
Map.
2.方法摘要
|
3 程序实例
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapInstance {
public static void main(String[] args) {
// 创建一个HashMap
Map<String, Integer> map = new HashMap<String, Integer>();
// 判断一个Map是否是空
System.out.println("--Is the map empty? --" + map.isEmpty());
// 向Map中添加几个键值对
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.put("D", 4);
map.put("E", 5);
// 获取Map的大小并打印Map
System.out.println("The size of Map is " + map.size());
System.out.println(map);
// 查看Map中是否存在某个键
System.out.println("Contains Key A :" + map.containsKey("A"));
System.out.println("Contains Key Z :" + map.containsKey("Z"));
// 查看Map中是否存在某个值
System.out.println("Contains Value 1 :" + map.containsValue(1));
System.out.println("Contains Value 10 :" + map.containsValue(10));
// 打印Map中的所有键及所有值
System.out.println(map.keySet());
System.out.println(map.values());
// 获取Map某个键对应的值,如果没有返回null
System.out.println(map.get("A"));
System.out.println(map.get("X"));
// 从Map中移除键为指定内容的键值对
System.out.println(map.remove("B"));
System.out.println(map);
// 将Map清空
map.clear();
System.out.println(map);
// 遍历hashMap的方法一(相对而言更高效)
Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key=" + key + "\t Value" + value);
}
// 遍历hashMap的方法二(相对而言效率比前者低一些)
Iterator<String> iterator2 = map.keySet().iterator();
while (iterator2.hasNext()) {
String key = iterator2.next();
Integer value = map.get(key);
System.out.println("Key=" + key + "\t Value" + value);
}
}
}