Reputation: 24248
Code:
public class MyClass {
private Map<Integer,String> myMap=new HashMap<Integer, String>();
...........................
void methodFillMap(){
myMap.put(.....);
.....................
}
}
What is correct:
void methodFillMap(){
myMap.clear();
myMap.put(.....);
.....................
}
or
void methodFillMap(){
myMap=null;
myMap.put(.....);
.....................
} or better
void methodFillMap(){
myMap=new HashMap<Integer, String>();
myMap.put(.....);
.....................
}
Upvotes: 3
Views: 2998
Reputation: 1721
The last one is the best one if you not coding for a system with very limited memmory then it's the first one that is best
Upvotes: 3
Reputation: 8278
The are not the same because map=nul does not nulify the map entries. map=null only nullifies the reference to the map. See the clear implementation from JDK 7 below:
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
I would use map.clear().
Upvotes: 2
Reputation: 23443
After setting the map to null, putting anything inside of it will result in a NullPointerException
.
Upvotes: 2
Reputation: 137322
NO. they are not the same.
map = null
assigns null to the Map reference.map.clear()
clears the content of the map, but the object still exists and map
still references to it.Upvotes: 8
Reputation: 543
void methodFillMap(){ myMap=null; myMap.put(.....);
will simply throw a NullPointerException.
To clear a map you should use myMap.clear().
By the way there are two differences between reinstantiating the map and using clear:
-clear won't resize the map. IF the HashMap contained n buckets, after a clear it will still contain n empty buckets, with performance consequences (positive or negative depending on your usage of the map)
-if you use clear you are not throwing away the object, thus it will not be managed through next GC, with impact (positive) on GC time if this happens a lot.
Upvotes: 7