Java协方差 [英] Java covariance

查看:181
本文介绍了Java协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决这个问题。说我有以下代码:

I'm having a hard time trying to figure this out. Say I have the following code:

class Animal { }
class Mammal extends Animal { }
class Giraffe extends Mammal { }
...
public static List<? extends Mammal> getMammals() { return ...; }
...

public static void main(String[] args) {
    List<Mammal> mammals = getMammals(); // compilation error
}

为什么分配会导致编译错误?错误类似于:

Why does the assignment result in a compilation error? The error is something like:

Type mismatch: cannot convert from List<capture#4-of ? extends Mammal> to List<Mammal>

根据我对协方差的理解, getMammals()方法返回列表,它将始终包含 Mammal 对象,因此它应该是可分配的。我缺少什么?

According to my understanding of covariance, the getMammals() method returns a list that will always contain Mammal objects so it should be assignable. What am I missing?

推荐答案

因为 getMammals 可能会返回列表< Giraffe> ,如果可以转换为列表< Mammal> ,那么你就可以添加 Zebra 。您不能被允许将 Zebra 添加到 Giraffe 的列表中,是吗?

Because getMammals could return a List<Giraffe>, and if that was convertable to List<Mammal> then you'd be able to add a Zebra to it. You can't be allowed to add a Zebra to a list of Giraffe, can you?

class Zebra extends Mammal { }

List<Giraffe> giraffes = new List<Giraffe>();

List<Mammal> mammals = giraffes; // not allowed

mammals.add(new Zebra()); // would add a Zebra to a list of Giraffes

这篇关于Java协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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