Java if三元运算符和Collections.emptyList()
你能解释为什么第一个返回类型的代码无法编译? 消息是: Type mismatch: cannot convert from List to List
Type mismatch: cannot convert from List to List
。
在第二种情况下是否插入了显式转换?
public class GenericsTest { private String getString() { return null; } public List 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, 三元运算符部分 ),但看起来三元表达式不会从返回类型推断出类型参数。
换句话说,三元表达式的类型取决于其操作数的类型。 但其中一个操作数具有未确定的类型参数( Collections.emptyList()
)。 此时,三元表达式仍然没有类型,因此它不会影响类型参数。 有两种类型需要推断 – 一种是三元表达式的结果,另一种是.emptyList()
方法的类型参数。
使用Collections.
显式设置类型
表达式flag ? trueCase : falseCase
的类型flag ? trueCase : falseCase
flag ? trueCase : falseCase
是两种情况中最常见的类型。
在这种情况下,最常见的Collections.emptyList()
和Collections.singletonList(someVariable)
是List extends Object>
List extends Object>
因为它不能“在将来看到” Collections.emptyList()
应该在表达式中返回List
。
当你这样做时:
return Collections.emptyList();
编译器可以是智能的,并通过返回类型检测类型并检查正确性(推断)。
因为Collections.emptyList()
不返回List
。 您将方法的结果显式设置为List
,这意味着您必须返回此类列表。
例如
return Collection.emptyList();
要么
return new ArrayList();
会工作得很好。