一、HashMap概述
- HashMap是一个散列表,它存储的是键值对(key-value)映射;
- HashMap继承AbstractMap,实现了Map,Cloneable,Serializable接口;
- HashMap的实现不是同步的,线程不安全,但是效率高;
- HashMap允许null键和null值,是基于哈希表的Map接口实现;
- 哈希表的作用是用来保证键的唯一性;
- HashMap的实例有两个参数影响其性能:初试容量和加载因子,当哈希表中的条目数超出加载因子与当前容量的乘积时,要对哈希表进行rehash操作(即重建内部数据结构),容量扩大约为之前的两倍,加载因子默认值为0.75;
二、HashMap的三种遍历方式
第一种:遍历HashMap的entrySet键值对集合
- 通过HashMap.entrySet()得到键值对集合;
- 通过迭代器Iterator遍历键值对集合得到key值和value值;
/*
第一种:遍历HashMap的entrySet键值对集合
1. 通过HashMap.entrySet()得到键值对集合;
2. 通过迭代器Iterator遍历键值对集合得到key值和value值;
*/
public static void main(String[] args) {
//创建一个key和value均为String的Map集合
Map<String, String> map = new HashMap<String, String>();
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
//键和值
String key = null;
String value = null;
//获取键值对的迭代器
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> next = it.next();
key = next.getKey();
value = next.getValue();
System.out.println("key:" + key + "---" + "value:" + value);
}
}
输出结果:
第二种:遍历HashMap键的Set集合获取值;
- 通过HashMap.keySet()获得键的Set集合;
- 遍历键的Set集合获取值;
/*
第二种:遍历HashMap键的Set集合获取值;
1. 通过HashMap.keySet()获得键的Set集合;
2. 遍历键的Set集合获取值;
*/
public static void main(String[] args) {
//创建一个key和value均为String的Map集合
Map<String, String> map = new HashMap<String, String>();
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
//键和值
String key = null;
String value = null;
//获取键值对的迭代器
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
key = it.next();
value = map.get(key);
System.out.println("key:" + key + "---" + "value:" + value);
}
}
输出结果:
第三种:遍历HashMap“值”的集合;
- 通过HashMap.values()得到“值”的集合
- 遍历“值”的集合;
/*
第三种:遍历HashMap“值”的集合;
1. 通过HashMap.values()得到“值”的集合
2. 遍历“值”的集合;
*/
public static void main(String[] args) {
//创建一个key和value均为String的Map集合
Map<String, String> map = new HashMap<String, String>();
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
//值
String value = null;
//获取键值对的迭代器
Iterator<String> it = map.values().iterator();
while (it.hasNext()) {
value = it.next();
System.out.println("value:" + value);
}
}
输出结果: