首页 > 解决方案 > 三元运算符与 Map NullPointerException Java

问题描述

这里的疑问是,如果地图中的键不存在,它会返回 null,而我正在尝试将其放入Integer.

import java.util.*;
class Main {
  public static void main(String[] args) {
    HashMap<String,Integer> hm =new HashMap<>();
    hm.put("abc",1);
    hm.put("xyz",1);
    System.out.println(hm.get("pqr"));
    Integer result = hm !=null ? hm.get("pqr") : 0;
    System.out.println(result);
  }
}

输出:

null
Exception in thread "main" java.lang.NullPointerException
    at Main.main(Main.java:10)

如果我将三元运算符拆分为if-elseLike:

import java.util.*;
public class TestMain {
    public static void main(String[] args) {
        HashMap<String,Integer> hm =new HashMap<>();
        hm.put("abc",1);
        hm.put("xyz",1);
        System.out.println(hm.get("pqr"));
        Integer result;
        if ( hm != null){
          result = hm.get("pqr");
        } else
            result =0;
        System.out.println(result);
    }
}

输出:

null
null

三元运算符出了什么问题?

标签: javanullpointerexceptionhashmapintegerconditional-operator

解决方案


三元条件表达式的类型

hm !=null ? hm.get("pqr") : 0

int,所以hm.get("pqr")(其值为null)被拆箱到int,这会抛出NullPointerException.

为了避免它,你可以写:

Integer result = hm !=null ? hm.get("pqr") : Integer.valueOf(0);

现在三元条件表达式的类型将是Integer,因此不会尝试 unbox hm.get("pqr"),也不例外。

确定三元条件运算符类型的逻辑可以在15.25 中找到。条件运算符 ? :Table 15.25-ATable 15.25-C


推荐阅读