在Java中转换内部条件运算符 [英] casting inside conditional operator in Java

查看:200
本文介绍了在Java中转换内部条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会在eclipse IDE中出现错误(在行号附近出现错误符号)

This give an error in eclipse IDE.(Error symbol appearing near the line number)

String[] allText = null;

之后,我做了一些东西,如初始化数组等。但根据一些条件。所以我想使用下面的条件运算符。

After this i have done some stuff like initialing the array and so on. But according to some conditions. So I want to use a conditional operator like below.

List<String> finalText = (allText != null) ?
    Arrays.asList(allText) : (List<String>) Collections.emptyList();

如果我把我的铸件在等号后面,它工作得很好)
这个错误的目的是什么呢?

If I put my casting just after the equal sign, it works well.(wrapping the full ternary operation) What is the purpose of this error to be come like this?

List<String> allHotels = (List<String>) ((allText != null) ?
    Arrays.asList(allText) : Collections.emptyList());


推荐答案

这是抱怨,因为编译器试图应用强制转换为三元运算符的第一部分,而不是整个表达式。所以这部分代码:

It is complaining because the compiler is trying to apply the cast to the first part of the ternary operator and not the entire expression. So this part of your code:

(List<String>) (allText != null)

这是要转换的内容,但(allText!= null)到布尔。要使转换工作,你需要包含整个表达式,如下:

This is what is being cast, but (allText != null) evaluates to a boolean. To make the cast work you need to encompass the entire expression, like this:

List<String> allHotels = (List<String>) ((allText != null) ?
Arrays.asList(allText) : Collections.emptyList());

请注意整个三元运算符的括号。

Note the parenthesis around the entire ternary operator.

你不应该实际上需要做转换,因为编译器会推断正确的类型执行 Collections.emptyList()

You shouldn't actually need to do the cast at all though as the compiler will infer the correct type when performing Collections.emptyList()

这篇关于在Java中转换内部条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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