HashMap 是什么?
HashMap
是 Java 集合框架(Collection Framework) 中的一个哈希表(Hash Table)实现,它存储键值对 (key-value
),并通过哈希函数快速查找、插入和删除数据。
- 键(Key):唯一,不可重复。(底层用
hashCode()
和equals()
方法判断是否相同) - 值(Value):可以重复,可为
null
。
如何使用 HashMap
1. 创建 HashMap
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// 创建一个 HashMap,键为 Integer,值为 String
HashMap<Integer, String> map = new HashMap<>();
}
}
2. put()
方法 - 添加键值对
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
System.out.println(map); // 输出: {1=Apple, 2=Banana, 3=Cherry}