About map.put () method, a null pointer exception reported java.lang.NullPointerException

In Java programming, from time to time you will encounter java.lang.NullPointerException exception, first look at the following code:

public class Test { 
private Map<String, String> map; 
public void test(){ 
map.put("1", "John"); 
map.put("2", "Lily"); 
System.out.println(map.toString()); 
	}

public static void main(String[] args) {  
        Test test = new Test();  
        test.test();  
	}  
} 

The code above will report an exception:
Exception in the Thread "main" java.lang.NullPointerException
problem lies in the map, although initialized, but the member variables initialized by default to null, and did not allocate memory, then be put on the map operation, bound News null pointer exception.
Solution is to initialize the map, you can modify the following code.

public class Test { 
private Map<String, String> map = new HashMap<>(); //重要是要分配内存!
    //private Map<String, String> map; 
    public void test(){ 
    map.put("1", "jichenxiao"); 
    map.put("2", "fanwenxiao"); 
    System.out.println(map.toString()); 
}

public static void main(String[] args) {  
        Test test = new Test();  
        test.test();  
	}  
}

Guess you like

Origin blog.csdn.net/weixin_45202377/article/details/91298676