HashMap and garbage collection: do I need to call

2019-05-25 06:58发布

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.

3条回答
Emotional °昔
2楼-- · 2019-05-25 07:20

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.

查看更多
再贱就再见
3楼-- · 2019-05-25 07:27

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));
}
查看更多
做个烂人
4楼-- · 2019-05-25 07:30

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.

查看更多
登录 后发表回答