Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting inside conditional operator in Java

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());
like image 244
Jude Niroshan Avatar asked Nov 01 '22 05:11

Jude Niroshan


2 Answers

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

like image 118
tddmonkey Avatar answered Nov 13 '22 03:11

tddmonkey


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());
like image 36
Tomek Avatar answered Nov 13 '22 01:11

Tomek