質問

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(.....);

  .....................
}
役に立ちましたか?

解決

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

  1. In the first case you have to clear the hashtabel whitch takes some computation.
  2. The secound won't even work since you just got a null reference and not a hashmap.
  3. In the third case you just throw away the old hashmap and let the garbage collector handle the old one.

他のヒント

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.

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.

After setting the map to null, putting anything inside of it will result in a NullPointerException.

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().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top