`

让人崩溃的代码,无法预测的结果

    博客分类:
  • Java
阅读更多
Integer color = null;
int white = 255 * 255 * 255;
color = false ? white : color;


你猜结果会是怎样呢?
运行一下看看吧,结果是否让人崩溃?

Integer color1 = 1000;
int color2 = 1000;
if(color1 == color2) {
    System.out.printeln("你没有疯。");
}

if(color2 == color1) {
    System.out.println("你很正常。");
}


上面代码结果又如何呢?
你真的能相信Java吗?无冕之王真的比草根语言严谨吗?
0
0
分享到:
评论
4 楼 yearn20m 2010-08-27  
PS:上个回复写错了点,
Integer color1 = 1000; 

应是
Integer color1 = null; 


靠 JE 不允许编辑评论啊
3 楼 yearn20m 2010-08-27  
这些都是java的自动装箱拆箱造成的
http://stackoverflow.com/questions/2615498/java-conditional-operator-result-type

color = false ? white : color; 

写成
color = false ? color : white;

就不会有问题

==========
当进行数值比较时,如果其中有操作数,都将被自动拆箱
所以改成
Integer color1 = 1000; 

那么后边的比较就会出问题

参见JSL(java语言规范)
15.21 Equality Operators
引用
If the operands of an equality operator are both of numeric type, or one is of
numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric
promotion is performed on the operands (§5.6.2).


==========
参考资料:
JSL
§5.1.8
§5.6.2
§15.21
§15.25

2 楼 小白·菜 2010-03-15  
xwkp2008 写道
理解了Integer和int的区别后你就不会觉的崩溃了

您应该没有亲手尝试一下上面的例子,结果肯定跟你想象的不一样。
1 楼 xwkp2008 2009-08-13  
理解了Integer和int的区别后你就不会觉的崩溃了

相关推荐

Global site tag (gtag.js) - Google Analytics