gpt4 book ai didi

java - ImmutableList.builder() 错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:51 25 4
gpt4 key购买 nike

我刚开始学习 Guava,我注意到 ImmutableList.builder() 有一些特别之处.

这不编译:

List<String> iList = ImmutableList.builder().add("One").add("Two").build(); 
//Type mismatch: cannot convert from List<Object> to List<String>

这个有效:

List<String> iList = new ImmutableList.Builder<String>().add("One").add("Two").build(); 

我可以忍受使用 new ImmutableList.Builder<String>()但这是 ImmutableList.builder() 的错误吗? ?

最佳答案

不,只是提供一个类型参数

List<String> iList = ImmutableList.<String>builder().add("One").add("Two").build(); 

这绝不是 Guava 中的错误,它只是 Java 语言的一个特性/限制。编译器无法推断 build() 的返回类型来自先前的方法调用或结果被分配给的变量的声明。

安吉丽卡·兰格 explains这个

Automatic type argument inference. The method is invoked like regularnon-generic methods, that is, without specification of the typearguments. In this case the compiler automatically infers the typearguments from the invocation context.

她在Why does the type inference for an instance creation expression fail? 中也给出了类似的例子。

String s = new ArrayList<>().iterator().next();  // error

和状态

In the example above an error message is issued because the new-expression new ArrayList<>() does not have constructor arguments and it neither appears on the right-hand side of an assignment nor asthe argument of a method invocation. Instead, it appears in a chainof method calls. Such a chain is not a valid type inference context.

关于java - ImmutableList.builder() 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22776711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com