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

问题描述

你能解释为什么第一个返回类型的代码不能编译?
消息是:类型不匹配:无法从List< capture#1-of转换? extends Object>到列表< String>



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

  public class GenericsTest {

private String getString(){
return null;
}

public List< String> method(){
String someVariable = getString();
//第一个返回类型
// return someVariable == null? Collections.emptyList():Collections.singletonList(someVariable);
//第二个返回类型
if(someVariable == null){
return Collections.emptyList();
} else {
return Collections.singletonList(someVariable);
}
}
}


解决方案>

因为类型推理规则。我不知道为什么确切(您应该检查JSL,),但三元表达式不会从返回类型推断类型参数。



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



使用集合。< String> emptyList()显式设置类型


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);
            }
        }
    }
解决方案

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.

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.

Use Collections.<String>emptyList() to explicitly set the type

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

10-22 15:12