具体信息请查看 API 帮助文档
1. 概述
HashMap 是 Java 中的一种集合类,它实现了 Map 接口。HashMap 使用键值对存储数据,每个键值对被称为一个 Entry(条目)。HashMap 使用哈希表来存储数据,因此能够在 O(1) 时间复杂度下进行插入、删除和查找操作。
HashMap 的特点包括:
-
键不重复:HashMap 中的键是唯一的,如果插入时有重复键,则后面的值会覆盖之前的值。
-
无序性:HashMap 中的元素没有固定的顺序,即不保证元素的顺序与插入的顺序一致。
-
允许空键和空值:HashMap 允许键和值都为 null。
-
非线程安全:HashMap 不是线程安全的,如果有多个线程同时访问一个 HashMap 对象并对其进行修改,可能会导致数据不一致或抛出异常。如果需要在多线程环境中使用,可以考虑使用 ConcurrentHashMap。
2. 方法
HashMap
集合是Map
集合的子类,因此Map
集合的方法HashMap
集合都能使用。
方法名 | 说明 |
---|---|
V put(K key,V value) | 添加元素 |
V remove(Object key) | 根据键删除键值对元素 |
void clear() | 移除所有的键值对元素 |
boolean containsKey(Object key) | 判断集合是否包含指定的键 |
boolean containsValue(Object value) | 判断集合是否包含指定的值 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中键值对的个数 |
3. 遍历方式
与共有的 集合遍历方式 一样
4. 代码示例1
- 代码示例
存储学生对象并遍历
需求:创建一个HashMap集合,键是学生对象(Student),值是籍贯(String)。存储三个键值对元素,并遍历集合
要求:同姓名,同年龄认为是同一个学生
package text.text02;
import java.util.*;
import java.util.function.BiConsumer;
/*
存储学生对象并遍历
需求:创建一个HashMap集合,键是学生对象(Student),值是籍贯(String)。存储三个键值对元素,并遍历集合
要求:同姓名,同年龄认为是同一个学生
*/
public class text49 {
public static void main(String[] args) {
//创建学生对象
Student7 student1 = new Student7("张三", 23);
Student7 student2 = new Student7("李四", 24);
Student7 student3 = new Student7("王五", 25);
Student7 student4 = new Student7("王五", 25);
//创建集合对象
HashMap<Student7, String> hm = new HashMap<>(); //键是自定义对象,必须要重写equals和hashCode方法
//添加集合元素
hm.put(student1, "山西");
hm.put(student2, "河南");
hm.put(student3, "湖北");
hm.put(student4, "湖北");
//遍历集合 、
//1.通过键找值的方式遍历
System.out.println("1.通过键找值的方式遍历:");
Set<Student7> set = hm.keySet();
Iterator<Student7> it = set.iterator();
while (it.hasNext()) {
Student7 key = it.next();
String value = hm.get(key);
System.out.println(key + " = " + value);
}
//2.通过键值对的方式遍历
System.out.println("2.通过键值对的方式遍历:");
Set<Map.Entry<Student7, String>> entries = hm.entrySet();
for (Map.Entry<Student7, String> map : entries) {
Student7 key = map.getKey();
String value = map.getValue();
System.out.println(key + " = " + value);
}
//3.通过结合Lambda表达式的方式遍历
System.out.println("3.通过结合Lambda表达式的方式遍历:");
hm.forEach(new BiConsumer<Student7, String>() {