本文介绍了Java if 三元运算符和 Collections.emptyList()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能解释一下为什么第一个返回类型的代码不能编译吗?消息是:Type mismatch: cannot convert from List到列表.

Could you please explain why with the first return type the code can't be compiled?The message is : Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>.

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

Is there inserted an explicit cast in the second case ?

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

推荐答案

因为类型推断规则.我不知道为什么完全(你应该检查 JSL,三元运算符部分),但看起来三元表达式没有从返回类型推断类型参数.

Because of type inference rules. I don't know why exactly (you should check the JSL, the ternary operator section), but it appears the ternary expression does not infer the type parameter from the return type.

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

In other words, the type of the ternary expression depends on the types of its operands. But one of the operands has undetermined type parameter (Collections.emptyList()). At that point the ternary expression still does not have a type, so it cannot influence the type parameter. There are two types to be inferred - one is the result of the ternary expression, and the other is the type parameter of the .emptyList() method.

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

这篇关于Java if 三元运算符和 Collections.emptyList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:01