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
It seems the memory is reduced when call the clear method. However, from looking at other answers it seems the clear method never shrinks the HashMap. So why is the memory reduced?