Java if三元运算符和Collections.emptyList()

StK*_*ler 12 java generics casting

你能解释为什么第一个返回类型的代码无法编译?消息是:Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>.

在第二种情况下是否插入了显式转换?

public class GenericsTest {

        private String getString() {
            return null;
        }

        public List<String> method() {
            String someVariable = getString();
            //first return type
            //return someVariable == null ? Collections.emptyList() : Collections.singletonList(someVariable);
            //second return type
            if (someVariable == null) {
                return Collections.emptyList();
            } else {
                return Collections.singletonList(someVariable);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 18

因为类型推断规则.我不知道为什么,究竟(你应该检查JSL,三元运算符节),但它出现在三元表达式不从返回类型推断类型参数.

换句话说,三元表达式的类型取决于其操作数的类型.但其中一个操作数具有未确定的类型参数(Collections.emptyList()).此时,三元表达式仍然没有类型,因此它不会影响类型参数.有两种类型可以推断 - 一种是三元表达式的结果,另一种是方法的类型参数.emptyList().

使用Collections.<String>emptyList()显式设置类型