【发布时间】:2018-03-26 19:46:50
【问题描述】:
我在开发过程中注意到了这一点。
为什么三元运算符在方法参数中不起作用?这里显然是InputStream 或(否则)String。
class A{
public static boolean opAlpha(InputStream inputStream) {
// Do something
return true;
}
public static boolean opAlpha(String arg) {
// Do something else
return true;
}
public static void main(String[] args) throws Exception {
boolean useIsr = true;
InputStream inputStream = null;
String arg = null;
// boolean isTrue = useIsr ? A.opAlpha(inputStream): A.opAlpha(arg); // This is OK.
boolean isTrue = A.opAlpha(useIsr ? inputStream : arg); // This is not. (Error : The method opAlpha(InputStream) in the type A is not applicable for the arguments (Object))
}
}
【问题讨论】:
-
这里没有运算符重载。
-
还有我一贯的迂腐评论:这不是三元运算符,而是conditional operator。确实它是 a 三元运算符(一个接受三个操作数的运算符),而且它确实是 Java 唯一的一个,但理论上在某些时候可能还有其他运算符...... :-)
-
谢谢 T.J.明白了!
标签: java ternary-operator