三目运算符的一个坑-自动拆箱

来源:互联网 发布:照片图库 mac 密码 编辑:程序博客网 时间:2024/06/05 20:02
问题描述:
             Integer a = null;

             Integer b = true ? a : 0

执行这个三目表达式后, b等于多少, 理解原因;


执行以上两行代码

  1. /**
  2. * Created by ryan01.peng on 2017/7/25.
  3. */
  4. public class TestTernaryOperator {
  5. public static void main(String[] args) {
  6. Integer a = null;
  7. Integer b = true ? a : 0; //这里是第10行,报错行 b.intValue();
  8. System.out.println(b);
  9. }
  10. }
会导致报错,如下

  1. Exception in thread "main" java.lang.NullPointerException
  2. at com.vip.vcp.ryan.zhaunzheng.leBasic.TestTernaryOperator.main(TestTernaryOperator.java:10)
  3. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  4. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  5. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  6. at java.lang.reflect.Method.invoke(Method.java:606)
  7. at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

分析:这里的报错出现在三目运算符所在的一行,而不是使用b的最后一行。说明这个NullPointerException并不是Integer b引起的,而是由于三目运算符所在行引起的。
这里空指针异常的原因是: 三目运算中只要后面两个元素是不同的类型,涉及到类型转换,那么编译器会往下(基本类型)转型,再进行运算。 就是说,如果运算中有int和Integer,Integer会先转成int再计算,在拆箱的过程中a=null转换成int,导致了NullPointerException。
我们将Integer b =true? a :0; 换为Integer b =true? a :new Integer(0);则不会抛出异常了。输出null

以后开发中避免的措施:
1. 对对象进行使用或者操作时都先验空,然后再进行操作处理。
2. 三目运算符后最好使用同种类型的对象。

原创粉丝点击