casting inside conditional operator in Java

你说的曾经没有我的故事 提交于 2019-12-10 13:44:30

问题


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());

回答1:


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)

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.

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




回答2:


Looking at java.util.Collections code, the emptyList() method looks like:

public static <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

When you will change your emptyList() to EMPTY_LIST it will be ok without any casting, but of course with warning (EMPTY_LIST is an instance of EmptyList class which is generic like all list classes). The issue is about the generic parameter, you have to set the type. You can do it that way if you want, with even no warnings:

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



回答3:


Following evaluates to be a bool.

(allText != null)

It is not clear how your cast can work. Error is correct.

 (List<String>) (true or false)

Following should be fine. (not sure if I got your question right)

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


来源:https://stackoverflow.com/questions/29964393/casting-inside-conditional-operator-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!