Casting inside a conditional statement in Java

This gives an error in the eclipse IDE (an error symbol appears next to the line number)

String[] allText = null; 

After that, I did some things, such as array initialization, etc. But according to some conditions. Therefore, I want to use a conditional operator as shown below.

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

If I put my casting right after the equal sign, it works well (completing the full triple operation) What is the purpose of this error?

 List<String> allHotels = (List<String>) ((allText != null) ? Arrays.asList(allText) : Collections.emptyList()); 
+5
source share
3 answers

He complains because the compiler is trying to apply the cast to the first part of the ternary operator, and not to the whole expression. So this part of your code:

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

This is what runs, but (allText != null) evaluates to boolean. To do a cast, you need to cover the whole expression, for example:

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

Note the brackets around the entire triple operator.

You don't really need to throw, but since the compiler will infer the correct type when you execute Collections.emptyList()

+1
source

After looking at the java.util.Collections code, the emptyList () method looks like this:

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

When you change your empty list () to EMPTY_LIST, this will be fine without castings, but of course with a warning (EMPTY_LIST is an instance of the EmptyList class, which is common, like all list classes). The problem is with the general parameter, you must set the type. You can do it this way if you want, even without warning:

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

The following rates as bool.

 (allText != null) 

It is unclear how your cast can work. The error is correct.

  (List<String>) (true or false) 

The following should be fine. (not sure if I received your question correctly)

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

All Articles