Map集合

Map


一、Map集合:

1.1 Map是什么?

  • 定义:Map是一种键值对(Key-Value)存储结构,类似字典——通过“键”快速查找“值”。
  • 特点
    • 键(Key)唯一,值(Value)可重复。
    • 键和值都可以为null(但不同Map实现类限制不同)。

类比

  • 键是字典的“单词”,值是“释义”。每个单词唯一,但不同单词可以有相同释义。

1.2 Map的四大实现类对比

特性HashMapLinkedHashMapTreeMapHashTable
顺序无序插入顺序自然/自定义排序无序
允许null键值键不能为null键和值都不能为null
线程安全不安全(高效)不安全(高效)不安全(高效)安全(低效)
底层结构数组+链表/红黑树链表+哈希表红黑树哈希表

1.3 常用操作示例

Map<String, String> heroes = new HashMap<>();
heroes.put("及时雨", "宋江");    // 添加键值对
heroes.put("豹子头", "林冲");
heroes.put("智多星", "吴用");

System.out.println(heroes.get("豹子头"));  // 输出:林冲
heroes.remove("智多星");                   // 删除键值对

// 遍历所有键值对
for (Map.Entry<String, String> entry : heroes.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

二、HashMap vs TreeMap:

2.1 HashMap

  • 适用场景:快速查询、无需排序。
  • 示例
    Map<String, Integer> scores = new HashMap<>();
    scores.put("小明", 90);
    scores.put("小红", 85);
    scores.put(null, 0);  // 允许null键
    

2.2 TreeMap

  • 适用场景:需要按键排序。
  • 示例
    // 按键的自然顺序(字母顺序)排序
    Map<String, String> sortedMap = new TreeMap<>();
    sortedMap.put("b", "Banana");
    sortedMap.put("a", "Apple");
    System.out.println(sortedMap);  // 输出:{a=Apple, b=Banana}
    

HashMap和HashTable有什么区别?

  • 线程安全:HashTable线程安全,HashMap不安全。
  • 性能:HashMap效率更高。
  • null支持:HashMap允许null键值,HashTable不允许。

如何选择Map的实现类?

  • 快速查询:选HashMap。
  • 需要排序:选TreeMap。
  • 多线程环境:用ConcurrentHashMap代替HashTable。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值