为什么 Java 7 和 Eclipse 3.8 编译器无法使用新的 Java 7 钻石运算符编译 JDK 代码?
import java.util.*;
public class SimpleArrays
{
@SafeVarargs
public static <T> List<T> asList( T... a )
{
return new ArrayList<>( a );
}
}
asList()
取自 java.util.Arrays 的 Oracle JDK 实现。
错误是
error: cannot infer type arguments for ArrayList<>
return new ArrayList<>( a );
1 error
这怎么行? Oracle 使用与我们相同的编译器。
import java.util.*;
public class SimpleArrays
{
@SafeVarargs
public static <T> List<T> asList( T... a )
{
return new ArrayList<>( a );
}
}
asList()
is taken from Oracles JDK implementation of java.util.Arrays.
The error is
error: cannot infer type arguments for ArrayList<>
return new ArrayList<>( a );
1 error
How can this work? Oracle uses the same compiler that we do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:
java.util.Arrays
类中使用的ArrayList
不是java.util.ArrayList
,而是嵌套类java.util.Arrays.ArrayList
。特别是,此类有一个以
T[]
作为参数的构造函数,而java.util.ArrayList
没有。也复制这个类,它就会起作用。
Attention: The
ArrayList
used in thejava.util.Arrays
class is notjava.util.ArrayList
, but a nested classjava.util.Arrays.ArrayList
.In particular, this class has an constructor which takes a
T[]
as argument, whichjava.util.ArrayList
does not have.Copy this class, too, and it will work.
据我所知,Eclipse 希望找到一种特定类型来推断模板化的 ArrayList。例如,如果您的方法的签名是:
Eclipse 将毫无问题地推断 ArrayList<>( a ) 的类型,并且会推断其类型为
Integer
。我相信菱形运算符应该以这种方式进行操作:推断特定类型,而不是模板化类型。幸运的是,您已经模板化了整个方法,以便您可以这样形成您的语句:
并且一切都会起作用:)。
From what I can gather, Eclipse wants to find a specific type to infer into the templated
ArrayList
. For example, if your method's signature was:Eclipse would have no problem inferring the type of
ArrayList<>( a )
, and would infer that its type isInteger
. I believe the diamond operator is meant to operate that way: to infer a specific type, not a templated one.Fortunately, you have templated the entire method, so that you could form your statement thus:
And everything would work :).