为什么在这种情况下为基本类型返回null? [英] Why does returning null for a primitive work in this case?

查看:101
本文介绍了为什么在这种情况下为基本类型返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段丑陋的代码确实可以编译,但是如果s == null

This ugly piece of code does compile but throws NPE if s == null

public static boolean isNullOrEmpty(String s)
{
    return s != null ? s.isEmpty() : null;
}

虽然这没有(按预期):

while this does not (as expected):

public static boolean isNullOrEmpty(String s)
{
    if(s != null)
        return s.isEmpty();
    else
        return null;
}

我知道他们两个都是错误的,但是当我在源代码中找到第一段代码时,我很惊讶它被编译了.

I know both of them are plainly wrong, but as I found the first piece of code in our sources, I was quite surprised it did compile.

这是Java 7中JLS的相关部分.我猜想第一个语句将适用,但粗体语句将适用.

Here's the relevant part of the JLS from Java 7. I guessed the first statement would apply but the bold one does.

15.25条件运算符? :

[...]

条件表达式的类型确定如下:

The type of a conditional expression is determined as follows:

[...]

  • 如果第二个操作数和第三个操作数之一是原始类型T,而另一个操作数的类型是将装箱转换(第5.1.7节)应用于T的结果,则条件表达式的类型是T./li>
  • If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

[...]

  • 否则,第二个操作数和第三个操作数的类型分别为S1和S2.让 T1是将装箱转换应用于S1所产生的类型,而让T2为 将装箱转换应用于S2所产生的类型. 条件表达式的类型是应用捕获的结果 转换(§5.1.10)到lub(T1,T2)(§15.12.2.7).
  • Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).

推荐答案

第一个具有三元运算符,其结果类型为Boolean. NPE正在将null转换为boolean.

The first has a ternary operator which has a result type of Boolean. The NPE is converting a null to a boolean.

实际上是这样的:

Boolean temp = s != null ? s.isEmpty() : null; //no problems here
return temp; //crash when temp==null

第二个试图返回错误的类型(对象而不是原始类型),因此无法编译.

The second is trying to return a wrong type (Object instead of primitive) - and thus does not compile.

这篇关于为什么在这种情况下为基本类型返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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