Unpacking and packing may appear pit

Take Integer as an example:


Use the static valueOf() method when boxing.

Use the non-static xxxValue() method when unpacking.

 try {
   int count = (Integer) map.get("count");
   } catch (NullPointerException e) {
     // do something.
 }
Copy the code

Why is a null pointer exception possible?

Map. get(“count”) returns the value of the map based on the key. It may get null, which can be converted to any type. Call intValue, a non-static method (the object’s method), and the variable is null, then a null-pointer exception occurs.

The test code

     public static void main(String[] args) {
         HashMap<String, Object> testInteger = new HashMap<>();
         testInteger.put("right", 1);
         testInteger.put("wrong", null);
 ​
         Integer wrong = (Integer) testInteger.get("wrong");
         int value = wrong.intValue();
         System.out.println(value);
     }
Copy the code