Casting List< Animal>列出< Dog> [英] Casting List<Animal> to List<Dog>

查看:82
本文介绍了Casting List< Animal>列出< Dog>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Animal.Class和Dog类,它扩展了Animal.Class



我可以知道是否有一种快速而简单的方法来做到这一点?

 列表< Dog> dogList = getAnimalList(); 

公共列表< Animal> getAnimalList(){
List< Animal> animalList = new LinkedList< Animal>();
return animalList;
}

除非绝对必要,否则我不希望再看整个动物列表。

为了其他检查目的,dog类只包含一个额外的布尔值。

解决方案

泛型继承与java继承原则稍有不同。您需要使用(通配符)

 列表< ;?延伸动物> dogList = getAnimalList(); 

编辑:

通配符指南:


  1. 使用extends关键字定义一个in变量,使用上界有界的通配符。
  2. 一个out变量用一个下界有界的通配符,使用super关键字。

  3. 在可以使用Object类中定义的方法访问in变量的情况下,使用无限制的通配符。

  4. 在代码需要以in和out变量访问变量的情况下,请勿使用通配符。


I have an Animal.Class and Dog class which extends Animal.Class

May I know if there is a quick and easy way to do this?

List<Dog> dogList = getAnimalList();

public List<Animal> getAnimalList(){
     List<Animal> animalList = new LinkedList<Animal>();
     return animalList;
}

I don't wish to look the entire animal List again unless absolutely necessary.

The dog class just contain an extra boolean value for other checking purpose.

解决方案

Generics inheritance is little different than java inheritance principle. You need to use ?(wildcards)

List<? extends Animal> dogList = getAnimalList();

EDIT:

Wildcard Guidelines:

  1. An "in" variable is defined with an upper bounded wildcard, using the extends keyword.
  2. An "out" variable is defined with a lower bounded wildcard, using the super keyword.
  3. In the case where the "in" variable can be accessed using methods defined in the Object class, use an unbounded wildcard.
  4. In the case where the code needs to access the variable as both an "in" and an "out" variable, do not use a wildcard.

这篇关于Casting List&lt; Animal&gt;列出&lt; Dog&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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