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

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 没有变小。

https://stackoverflow.com/questions/73363072/

相关文章:

python - 我有一个列表,其中每个元素都是列表中的单个数字。如何提取数字?

c++ - 带 abs() 的方程给出了错误的答案 (gcc/g++)

python - if 语句条件不适用于循环中的最后一个 i

python - 删除文本文件中每一行的最后一个字符

swiftui - .previewLayout(PreviewLayout.fixed(width

c++ - 指针 vector 未定义行为

string - Strip() 在 Julia 中工作很奇怪

python - 如何从不同文件导入和调用 'main'函数

regex - 使用先行正则表达式替换文本

go - context.TODO() 或 context.Background(),我更喜欢哪一个