2012-02-23 66 views
16

可能重复:
Tricky ternary operator in Java - autoboxing的Java零为int条件运算问题

我们知道int roomCode = null;不是由编译器允许在。

然后为什么代码1没有给出编译器错误,当代码2。

代码1:

int roomCode = (childCount == 0) ? 100 : null; 

代码2:

int roomCode = 0; 
if(childCount == 0) roomCode = 100; 
else roomCode = null; // Type mismatch: cannot convert from null to int 
+1

一个很好的问题。 – 2012-02-23 05:54:12

+1

也许与自动装箱相关,但我不知道如何... – talnicolas 2012-02-23 05:56:25

+0

当它采用该路径时,null值会作什么评估? – Mysticial 2012-02-23 05:58:35

回答

11

我做了一些调试和发现,评估

(childCount == 0) ? 100 : null; 

程序时调用整型的方法valueOf以评估null。它返回一个Integer,并且Integer可以是null(而不是int),它会进行编译。就好像你在做类似的事情:

int roomCode = new Integer(null); 

所以它与自动装箱有关。

+0

非常好的答案! – Deepak 2012-02-23 06:20:39