条件表达式陷阱

Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o);

 上面代码会打印什么?相信很多人都会觉得打印:1。

 认为它等同于: 

Object o2;
 
if (true)
    o2 = new Integer(1);
else
    o2 = new Double(2.0);

System.out.println(o2);

做测试发现第一段代码打印:1.0。第二段代码打印:1。

查阅条件运算符规则,总结核心三点:

1、如果第2个和第三个有相同的类型,那么它就是条件表达式的类型。

2、如果一个操作数的类型是T,T为byte、short、char,而另一个操作数是一个int类型的 常量 表达式时,如果条件表达式的类型为T时,结果为类型T。

3、否则将对操作数类型运用2进制数字提升,而表达式的类型就是第二个和第三个操作数被提升后的类型。

原来第一段代码的类型被提升为Double类型了,继续做更多的测试:

Object o = true ? new Byte("1") : new Short("2");
Object o1 = true ? new Short("1") : new Integer("2");
Object o2 = true ? new Integer(1) : new Double(2.0);
Object o3 = true ? new Integer(1) : new Float(2.0);
Object o4 = true ? new Double(2.0) : new Float(2.0);
Object o5 = true ? new Byte("1") : 2;
Object o6 = true ? 1 : new Float(2.0);
Object o7 = true ? 1 : new Short("2");
Object o8 = true ? 1 : 2.0;
byte x = 1;
Object o9 = true ? x : 2;
Object o10 = true ? x : new Integer("2");
System.out.println("o=" + o + " 类型:" + o.getClass());
System.out.println("o1=" + o1 + " 类型:" + o1.getClass());
System.out.println("o2=" + o2 + " 类型:" + o2.getClass());
System.out.println("o3=" + o3 + " 类型:" + o3.getClass());
System.out.println("o4=" + o4 + " 类型:" + o4.getClass());
System.out.println("o5=" + o5 + " 类型:" + o5.getClass());
System.out.println("o6=" + o6 + " 类型:" + o6.getClass());
System.out.println("o7=" + o7 + " 类型:" + o7.getClass());
System.out.println("o8=" + o8 + " 类型:" + o8.getClass());
System.out.println("o9=" + o9 + " 类型:" + o9.getClass());
System.out.println("o10=" + o10 + " 类型:" + o10.getClass());

 打印:

o=1 类型:class java.lang.Short

o1=1 类型:class java.lang.Integer

o2=1.0 类型:class java.lang.Double

o3=1.0 类型:class java.lang.Float

o4=2.0 类型:class java.lang.Double

o5=1 类型:class java.lang.Byte

o6=1.0 类型:class java.lang.Float

o7=1 类型:class java.lang.Short

o8=1.0 类型:class java.lang.Double

o9=1 类型:class java.lang.Byte

o10=1 类型:class java.lang.Integer

在条件表达式两个类型不同的情况下,除了byte、short、char以外,表达式的类型都被自动提升了。记住上面三点,防止条件表达式陷阱。

猜你喜欢

转载自huxu1986-163-com.iteye.com/blog/2171063