HashMap详解

①特性

  • 非线程安全
  • hashMap的映射不是有序的
  • key、value都可以为null

②常用方法

  • get(Object key)
  • put(Object key,Object value)
  • remove(Object key)
  • remove(Object key,Object value)
  • isEmpty()
  • size()
  • clone()
  • clear()
  • entrySet()
  • keySet()
  • values()
  • containsKey(Object key)
  • containsValue(Object value)
  • getOrDefault(Object key,Object defaultValue)
  • replace(Object key,Object oldValue,Object newValue)
  • replace(Object key,Object value)
  • replaceAll(BigFunction function)
  • putAll(Map m)
  • putIfAbsent(Object key,Object value)
  • compute(Objetc key,BigFunction bf)
  • computeIfAbsent(Object key,Function f)
  • computeIfPresent(Object key,BigFunction bf)
  • merge(Object key,Object value,BigFunction bf)

get/put/remove/isEmpty/size

 @Test
    public void test() {
        HashMap<String, Integer> map = new HashMap();
        map.put("key1", 1);
        map.put("key2", 2);
        System.out.println(map);
        System.out.println("key1 的值" + map.get("key1"));
        map.remove("key1");
        map.remove("key2", 3);
        System.out.println(map);
        System.out.println(map.isEmpty());
        System.out.println("map size" + map.size());
        map.remove("key2", 2);
        System.out.println(map.isEmpty());
    }

clone/clear

 public void test2() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("key1", 1);
        map.put("key2", 2);
        HashMap<String, Integer> cloneMap = (HashMap) map.clone();
        System.out.println(map);
        System.out.println(cloneMap);
        cloneMap.remove("key1");
        System.out.println(map);
        System.out.println(cloneMap);
        map.clear();
        cloneMap.clear();
        System.out.println(map);
        System.out.println(cloneMap);
    }

entrySet/keySet/values

 @Test
    public void test3() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("key1", 1);
        map.put("key2", 2);
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
        for (String key : map.keySet()) {
            System.out.println(key);
        }
        for (Integer value : map.values()) {
            System.out.println(value);
        }
    }

containsKey/containsValue

  @Test
    public void test4() {
        HashMap<String, Student> map = new HashMap<>();
        Student ryan = new Student(18);
        map.put("Ryan", ryan);
        System.out.println(map.containsKey("Ryan"));
        System.out.println(map.containsKey("ryan"));
        System.out.println(map.containsValue(ryan));
    }

getOrDefault

@Test
    public void test5() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("key1", 1);
        System.out.println(map.get("key1"));
        Integer n = map.getOrDefault("key1", 2);//map 中存在key = "key1" 返回对应的值,否则返回 2
        Integer  m = map.getOrDefault("key2",2);
        System.out.println(n);
        System.out.println(m);
    }

replace

@Test
    public void test6() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("key1", 1);
        map.put("key2", 2);
        System.out.println(map);
        map.replace("key1", 1, 4);
        System.out.println(map);
        map.replace("key2", 5);
        System.out.println(map);
        //replaceAll 对集合中的键值对进行计算
        map.replaceAll((k, v) -> {
            System.out.println(k);
            System.out.println(v);
            return null;
        });
    }

putAll/putIfAbsent

@Test
    public void test7() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("key1", 1);
        HashMap<String, Integer> map2 = new HashMap<>();
        map.put("key2", 2);
        map.putAll(map2);
        System.out.println(map);
        map.putIfAbsent("key1", 2);
        map.putIfAbsent("key3", 3);
        System.out.println(map);
    }

merge/computeIfAbsent

https://blog.youkuaiyun.com/mengxb12138/article/details/80893937

 

 

### HashMap 的工作原理与实现机制 HashMap 是 Java 中实现 Map 接口的常用类,它基于哈希表(Hash Table)实现,提供了高效的键值对存储和访问机制。其核心原理包括哈希计算、数组与链表/红黑树的结合结构、以及动态扩容机制。 #### 哈希表的基本结构 HashMap 的底层结构是一个数组,数组的每个元素称为“桶”(bucket)。每个键值对在插入时会通过哈希函数计算出一个哈希值,该值用于确定键值对应存储在数组的哪个位置。为了提高效率,HashMap 底层数组的长度总是 2 的幂次方,这样可以通过 `h & (table.length - 1)` 快速定位桶的位置,其中 `h` 是键的哈希值。这种设计是 HashMap 在性能优化上的关键手段之一[^2]。 #### 链表与红黑树的结合 当多个键的哈希值映射到同一个桶时,就会发生哈希冲突。为了解决冲突,HashMap 在每个桶中使用链表存储多个键值对。当链表长度超过阈值(默认为 8)时,链表会转换为红黑树,以提高查找效率。而当树的节点数小于阈值(默认为 6)时,红黑树又会退化为链表。这种结构在冲突较多时能显著提升性能[^1]。 #### 扩容机制 当 HashMap 中的元素数量超过当前容量与负载因子(load factor,默认为 0.75)的乘积时,会触发扩容操作。扩容时会创建一个新的数组,新数组的容量通常是原数组的两倍,并将所有键值对重新哈希分配到新的桶中。在重新哈希过程中,链表或红黑树会被拆分成两部分,分别放入新数组的 `j` 和 `j + oldCap` 位置,其中 `j` 是原桶的位置,`oldCap` 是原数组的长度。这一机制确保了扩容后数据分布的均匀性[^3]。 #### 线程安全性 HashMap 不是线程安全的。在多线程环境下,如果多个线程同时修改 HashMap 的结构(如 put 或 remove),可能会导致数据不一致或死循环等问题。因此,在并发场景下应使用 `ConcurrentHashMap` 或通过外部同步机制来保证线程安全[^4]。 #### 示例代码:HashMap 的基本使用 ```java import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); System.out.println("Value for 'apple': " + map.get("apple")); // 输出 1 System.out.println("Contains 'banana'? " + map.containsKey("banana")); // 输出 true System.out.println("Size of map: " + map.size()); // 输出 3 } } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值