简体   繁体   中英

Why static hashmap is always null in below case

// sampleMap is always null even though first time initialized in addMap method

public class Sample {

private static HashMap<Long, Long> sampleMap;

public Sample() {
    addToMap(sampleMap, 100L, 100L);
    addToMap(sampleMap, 200L, 200L);
    addToMap(sampleMap, 300L, 300L);
    addToMap(sampleMap, 400L, 400L);
}

public HashMap<Long, Long> getSampleMap() {
    return sampleMap;
}

private void addToMap(HashMap<Long, Long> map, Long key, Long value) {
    if (map == null) {
        map = new HashMap<Long, Long>();
    }
    map.put(key, value);
}

public static void main(String[] args) {
    Sample obj = new Sample();
    obj.getSampleMap();
}

}

addToMap creates a HashMap instance and assigns it to a local variable. It doesn't change the value of the sampleMap static variable.

Java is a pass by value language. Therefore, when you pass a variable to a method, the method can't change the value of that variable. If the method assigns a new value to the variable, this assignment is local to the method, and doesn't change the value of the original variable passed to the method.

You have several options. Here are some of them :

Initialize sampleMap when it is declared :

private static HashMap<Long, Long> sampleMap = new HashMap<Long, Long>();

or initialize sampleMap before first calling addToMap :

public Sample() {
    sampleMap = new HashMap<Long, Long>();
    addToMap(sampleMap, 100L, 100L);
    addToMap(sampleMap, 200L, 200L);
    addToMap(sampleMap, 300L, 300L);
    addToMap(sampleMap, 400L, 400L);
}

or don't pass sampleMap to addToMap . addToMap can access it directly :

private void addToMap(Long key, Long value) {
    if (sampleMap == null) {
        sampleMap = new HashMap<Long, Long>();
    }
    sampleMap.put(key, value);
}

One last thing. It makes little sense for an instance method to return a static member. Either make getSampleMap() static, or make sampleMap an instance variable (ie non static). The same is relevant for addToMap() .

Java is always pass-by-value . You can't reassign a reference inside a method.

That being said, there is no need to pass map to the adMap method. Just use the static sampleMap directly :

private void addToMap(Long key, Long value) {
    if (sampleMap== null) {
        sampleMap= new HashMap<Long, Long>();
    }
    sampleMap.put(key, value);
}

You can then alter your construcotr as :

public Sample() {
    addToMap(100L, 100L);
    addToMap(200L, 200L);
    addToMap(300L, 300L);
    addToMap(400L, 400L);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM