HashMap and garbage collection: do I need to call clear() before variable re-assignment?

℡╲_俬逩灬. 提交于 2019-12-22 13:58:40

问题


Maybe it's a silly question but I'm not sure about the garbage collection process.

Consider this code:

private HashMap<String, Parameter> configuration = new HashMap<String, Parameter>();

...
//add some items to configuration
...

//now get another configuration
HashMap<String, Parameter> parameters = new HashMap<String, Parameter>();
for (String parameterName : configurationParameterNameList) {
    parameters.put(parameterName, reader.readParameter(parameterName));
}

//and reassign the variable
this.configuration.clear();
this.configuration = parameters;

Do I need to call configuration.clear() before reassign it? Parameter class contains only a few String variables inside.


回答1:


No, you don't need to call clear().

As long as nothing else has a reference to that HashMap it (and all of its entries) will become eligible for garbage collection as soon as you change this.configuration to another value.




回答2:


There's no need. The original HashMap instance will be lost anyway. Initializing configuration doesnt make sense either.

private HashMap<String, Parameter> configuration;   
...
configuration = new HashMap<String, Parameter>();
for (String parameterName : configurationParameterNameList) {
    configuration.put(parameterName, reader.readParameter(parameterName));
}



回答3:


No, garbage collection in java is automatic. This means that if an object does not have a reference to it, it will be gotten rid of. So, like the above answer said, as soon as you take all the references away from the Map, it will become eligible for garbage collection.



来源:https://stackoverflow.com/questions/17027946/hashmap-and-garbage-collection-do-i-need-to-call-clear-before-variable-re-ass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!