gpt4 book ai didi

java - HashMap.clear() 减少内存?

转载 作者:行者123 更新时间:2023-12-05 08:24:44 25 4
gpt4 key购买 nike

System.gc();
System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024/1024);// print 1M

Map map=new HashMap();
for(int i=0;i<100000;i++){
map.put("key"+i,"i");
}
System.gc();
System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024/1024); //print 10M

map.clear();
System.gc();
System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));//print less than 1M

似乎调用clear方法时内存减少了。但是,从其他答案来看,clear 方法似乎永远不会缩小 HashMap。那么为什么内存会减少呢?

最佳答案

如果您指的是 this question's answers ,他们告诉您 HashMap 中的条目数组 (table) 永远不会缩小。相反,它的条目都设置为 null

但是清除 map 会使您创建的 100,000 个字符串("key0""key1"、...)及其关联的 Map.Entry 符合垃圾回收条件的对象,尽管 table 没有变小。

关于java - HashMap.clear() 减少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73363072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com