hashMap优化方法总结

hashMap 默认 是16的数组长度,非常的耗费内存

如果知道了数据具体的数量,并且指定 hashMap 的 具体容量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@SneakyThrows
    @Test
    void printHashMap() {
        Map<String, Object> mp = new HashMap<>();
        mp.put("data", 1);
        mp.put("res", 2);
        System.out.println();
        System.out.println(mp);
        Class<? extends Map> clazz = mp.getClass();
        Field f = clazz.getDeclaredField("table");
        f.setAccessible(true);
        Object list = f.get(mp);
        System.out.println(Arrays.deepToString((Object[]) list));
    }


    @Test
    void printMap2() throws NoSuchFieldException, IllegalAccessException {

        Map<String, Object> mp = new HashMap<>(2,0.75f);
        mp.put("data",1);
        mp.put("res",2);
        System.out.println();
        System.out.println(mp);
        Class<? extends Map> clazz = mp.getClass();
        Field f = clazz.getDeclaredField("table");
        f.setAccessible(true);
        Object list = f.get(mp);
        System.out.println(Arrays.deepToString((Object[]) list));

    }
    @Test
    void printMap3() throws NoSuchFieldException, IllegalAccessException {

        Map<String, Object> mp = new HashMap<>(2,2f);
        mp.put("data",1);
        mp.put("res",2);
        mp.put("res2",2);
        mp.put("res3",2);
        mp.put("res9",2);
        System.out.println();
        System.out.println(mp);
        Class<? extends Map> clazz = mp.getClass();
        Field f = clazz.getDeclaredField("table");
        f.setAccessible(true);
        Object list = f.get(mp);
        System.out.println(Arrays.deepToString((Object[]) list));

    }

这里设置了 数组长度和加载因子