我的代码有什么问题?空指针异常 [英] What is wrong with my code? NullPointerException

查看:70
本文介绍了我的代码有什么问题?空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有什么问题?它会在执行时抛出 NullPointerException.

What is wrong with the below code? It will throw NullPointerException while execution time.

public class Test
{
  public String method1()
  {
    return null;
  }
  public Integer method2()
  {
    return null;
  }
  public static void main(String args[])throws Exception
  {
    Test m1 = new Test();
    Integer v1 = (m1.method1() == null) ? m1.method2() : Integer.parseInt(m1.method1());
  }
}

推荐答案

a 的类型?b : c 是最后一个值 c 的类型.在这种情况下,它是一个 int.这意味着即使 b 被选中,它也会被拆箱,然后重新装箱成一个整数.由于该值为空,因此失败.

The type of a a ? b : c is the type of the last value c. In this case it's an int. This means that even though b is being chosen it is being unboxed and then re-boxed into an Integer. As the value is null, this fails.

这是一个类似的例子,它可能会有所帮助(或更令人困惑)

Here is a similar example which may help (or be more confusing)

Integer i = 1000;

// same as Integer j = Integer.valueOf(i == 1000 ? i.intValue() : 1000);
Integer j = i == 1000 ? i : 1000;
System.out.println(i == j);

Integer k = i == 1000 ? i : (Integer) 1000;
System.out.println(i == k);

印刷品

false
true

第一个结果为假的原因是表达式的类型为 int(最后一个参数),这意味着 i 被拆箱为 int 并重新装箱,以便将其分配给整数.这会产生一个不同的对象(有命令行参数会增加缓存大小并改变它)在第二个例子中,类型是 Integer 所以它没有被取消装箱并且对象是相同的.

The reason the first result is false, is that expression has a type of int (the last argument) which means i is unboxed to be an int and reboxed so it can be assigned to the Integer. This results in a different object (There are command line args which would increase the cache size and change this) In the second example the type is Integer so it is not unboxed and the object is the same.

这篇关于我的代码有什么问题?空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆