[英]Why can't the Java 7 and Eclipse 3.8 compiler compile JDK code with the new Java 7 diamond operator?
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. asList()
取自 java.util.Arrays 的 Oracle JDK 实现。
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.
Oracle 使用与我们相同的编译器。
Attention: The ArrayList
used in the java.util.Arrays
class is not java.util.ArrayList
, but a nested class java.util.Arrays.ArrayList
. Attention: The
ArrayList
used in the java.util.Arrays
class is not java.util.ArrayList
, but a nested class java.util.Arrays.ArrayList
.
In particular, this class has an constructor which takes a T[]
as argument, which java.util.ArrayList
does not have.特别是,这个 class 有一个以
T[]
作为参数的构造函数,而java.util.ArrayList
没有。
Copy this class, too, and it will work.也复制这个 class,它会起作用。
From what I can gather, Eclipse wants to find a specific type to infer into the templated ArrayList
.据我所知, Eclipse 想要找到一个特定类型来推断模板化的
ArrayList
。 For example, if your method's signature was:例如,如果您的方法的签名是:
public static List<Integer> asList( Integer... a )
Eclipse would have no problem inferring the type of ArrayList<>( a )
, and would infer that its type is Integer
. Eclipse 推断
ArrayList<>( a )
的类型没有问题,并且推断其类型为Integer
。 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:幸运的是,您已经对整个方法进行了模板化,因此您可以这样形成您的语句:
return new ArrayList<T>( a );
And everything would work:).一切都会奏效:)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.