Java中的棘手三元运算符 [英] Tricky ternary operator in Java

查看:53
本文介绍了Java中的棘手三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码段让我们看一下简单的Java代码:

 最终 公共  class 主要
{
     私有  int  temp()
     {
         返回(true吗?null: 0 ); // 没有编译器错误-编译器允许
                                   // 在方法签名中返回null值
                                   // 返回一个整数.
     }

     私有  int  same()
     {
          如果(真)
          {
               返回(空); //  if和if都不会导致
                              // 编译时错误-类型不兼容.
          }
          其他
          {
               返回( 0 );
          }
     }

     公共 静态  void  main(字符串 []参数)
     {
          Main m = new Main();
          System.out.println(m.temp());
          System.out.println(m.same());
     }
} 


在这种最简单的Java代码中,即使方法的返回类型为inttemp()方法也不会发出编译器错误,并且我们正在尝试返回值null(通过语句return(true ? null : 0);).编译时,显然会导致运行时异常NullPointerException.

但是,如果我们用if语句(如same()方法中)表示三元运算符,那似乎是不对的,它确实会发出编译时错误!为什么?

解决方案

条件运算符?:的返回值 type 很难处理(请参见 [final public class Main { private int temp() { return(true ? null : 0); // No compiler error - the compiler allows a //return value of null in a method signature //that returns an int. } private int same() { if(true) { return(null); // The same is not possible with if, and causes a //compile-time error - incompatible types. } else { return(0); } } public static void main(String[] args) { Main m=new Main(); System.out.println(m.temp()); System.out.println(m.same()); } }


In this simplest of Java code, the temp() method issues no compiler error even though the return type of the method is int, and we are trying to return the value null (through the statement return(true ? null : 0);). When compiled, this obviously causes the run time exception NullPointerException.

However, it appears that the same thing is wrong if we represent the ternary operator with an if statement (as in the same() method), which does issue a compile-time error! Why?

解决方案

The return value type of the conditional operator ?: is tricky (see "Conditional Operator ?:" in the Java specification[^]). If I got i,t then, in your case, the type int is assigned to ?: return value (maybe after boxing of both null an 0).


这篇关于Java中的棘手三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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