java 有没有办法强制 Arrays.asList 的返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15799359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to force the return type of Arrays.asList
提问by Troy Daniels
I have a method returning a collection of a base class:
我有一个方法返回一个基类的集合:
import java.util.*;
class Base { }
class Derived extends Base { }
Collection<Base> getCollection()
{
return Arrays.asList(new Derived(),
new Derived());
}
This fails to compile, as the return type of Arrays.asList
(List<Derived>
) does not match the return type of the method (Collection<Base>
). I understand why that happens: since the generic types are different, the two classes are not related by inheritance.
这将无法编译,因为Arrays.asList
( List<Derived>
) 的返回类型与方法 ( Collection<Base>
)的返回类型不匹配。我理解为什么会发生这种情况:由于泛型类型不同,这两个类没有通过继承相关联。
There are many ways to fix the compiler error from changing the return type of the method to not using Arrays.asList to casting one of the derived objects to Base.
有很多方法可以修复编译器错误,从将方法的返回类型更改为不使用 Arrays.asList 到将派生对象之一转换为 Base。
Is there a way to tell the compiler to use a different but compatible type when it resolves the generic type for the Arrays.asList call? (I keep trying to use this pattern and running into this problem, so if there is a way to make it work, I would like to know it.)
有没有办法告诉编译器在解析 Arrays.asList 调用的泛型类型时使用不同但兼容的类型?(我一直在尝试使用这种模式并遇到了这个问题,所以如果有办法让它工作,我想知道。)
I thought that you could do something like
我以为你可以做类似的事情
Collection<Base> getCollection()
{
return Arrays.asList<Base>(new Derived(),
new Derived());
}
When I try to compile that (java 6), the compiler complains that it is expecting a ')' at the comma.
当我尝试编译它 (java 6) 时,编译器抱怨它在逗号处需要一个 ')'。
回答by rgettman
Your syntax is almost correct; the <Base>
goes before the method name:
你的语法几乎是正确的;在<Base>
方法名称之前:
return Arrays.<Base>asList(new Derived(),
new Derived());
Java 8
爪哇 8
For Java 8, with its improved target type inference, the explicit type argument is not necessary. Because the return type of the method is Collection<Base>
, the type parameter will be inferred as Base
.
对于 Java 8,由于其改进的目标类型推断,不需要显式类型参数。因为方法的返回类型是Collection<Base>
,类型参数将被推断为Base
。
return Arrays.asList(new Derived(),
new Derived());
The explicit type parameter is still necessary for Java 7 and below. You can still supply the explicit type parameter in Java 8; it's optional.
Java 7 及以下版本仍然需要显式类型参数。您仍然可以在 Java 8 中提供显式类型参数;它是可选的。