有没有办法强制Arrays.asList的返回类型 [英] Is there a way to force the return type of Arrays.asList

查看:451
本文介绍了有没有办法强制Arrays.asList的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法返回一个基类的集合:

  import java.util。*; 
class Base {}
class Derived extends Base {}

Collection< Base> getCollection()
{
返回Arrays.asList(new Derived(),
Derived());
}

无法编译,因为返回类型 Arrays.asList ( List< Derived> )与方法的返回类型( Collection< Base> / code>)。我明白为什么会发生这种情况:因为泛型类型是不同的,所以这两个类不会被继承关联。



有很多方法可以修改编译器错误不使用Arrays.asList将其中一个派生对象转换为Base的方法的类型。

有没有办法告诉编译器在解析Arrays.asList调用的泛型类型时使用不同但兼容的类型? (我一直试图使用这种模式并遇到这个问题,所以如果有办法让它工作,我想知道它。)



我想你可以做一些类似的事情:

 集合< Base> getCollection()
{
返回Arrays.asList< Base>(new Derived(),
Derived());
}

当我尝试编译那个(java 6)时,编译器会抱怨它在逗号处期待''''。

解决方案

你的语法几乎是正确的; < Base> 位于方法名称之前:

  return Arrays 。< Base> asList(new Derived(),
Derived());

Java 8

对于Java 8,其改进的目标类型推断 ,显式类型参数不是必需的。因为方法的返回类型是 Collection< Base> ,所以type参数将被推断为 Base p>

 返回Arrays.asList(new Derived(),
Derived());

显式类型参数对于Java 7及更低版本仍然是必需的。您仍然可以在Java 8中提供显式类型参数;它是可选的。


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.

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.

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.)

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.

解决方案

Your syntax is almost correct; the <Base> goes before the method name:

return Arrays.<Base>asList(new Derived(),
                           new Derived());

Java 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.

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.

这篇关于有没有办法强制Arrays.asList的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆