简体   繁体   English

将子类对象添加到超类列表

[英]Adding subclass object to superclass list

I have a method that takes a list of a super class (Specifically my class Mob). 我有一个方法,需要一个超类的列表(特别是我的Mob类)。 It looks like this: 看起来像这样:

List<? extends Mob> mobs

I want to be able to add any object which extends the super class Mob to this list, like this: 我希望能够添加将超类Mob扩展到此列表的任何对象,如下所示:

spawnMob(new Zombie(World.getInstance(), 0, 0), World.getInstance().getZombies());

Where this is the method in question: 这里是有问题的方法:

public static void spawnMob(Mob mob, List<? extends Mob> mobs){
    mobs.add(mob);
}

This line of code World.getInstance().getZombies() returns a List of the object Zombie. 这行代码World.getInstance().getZombies()返回对象Zombie的列表。 Zombie extends Mob. 僵尸扩展了暴民。

However, this line of code: 但是,以下代码行:

mobs.add(mob);

Throws this error: 引发此错误:

The method add(capture#1-of ? extends Mob) in the type List<capture#1-of ? extends Mob> is not applicable for the arguments (Mob)

What can I do to resolve this? 我该怎么解决?

Edit, after changing the method to except List<Mob> I receive this error: 在将方法更改为List<Mob>以外的方法后进行编辑,我收到此错误:

The method spawnMob(Mob, List<Mob>) in the type MobSpawner is not applicable for the arguments (Zombie, List<Zombie>)

You cannot add anything but null to a List specified with an upper bounded wildcard. 除了null ,您不能将其他任何内容添加到使用上限通配符指定的List A List<? extends Mob> List<? extends Mob> List<? extends Mob> could be of anything that extends Mob . List<? extends Mob>可以是扩展Mob的任何东西。 It could be a List<Mafia> for all the compiler knows. 对于所有编译器来说,它都可以是List<Mafia> You shouldn't be able to add a Zombie to a List that could be a List<Mafia> . 你不应该能够添加一个ZombieList ,可能是一个List<Mafia> To preserve type safety, the compiler must prevent such calls. 为了保持类型安全,编译器必须阻止此类调用。

To add to such a list, you must remove the wildcard. 要添加到此类列表,必须删除通配符。

public static void spawnMob(Mob mob, List<Mob> mobs){

If you might have to pass in List s with specific subclasses, then consider making the method generic: 如果您可能必须传递带有特定子类的List ,请考虑使该方法通用:

public static <T extends Mob> void spawnMob(T mob, List<T> mobs){

尝试使用List<Mob> mobs

You can just declare the list as List<Mob> mobs , and any subclass of Mob will be accepted. 您可以将列表声明为List<Mob> mobs ,然后将接受Mob任何子类。 Note that when you get items from the list, you will only know for certain that they are of type Mob . 请注意,当您从列表中获取项目时,您将只能确定它们是Mob类型。 You will have to do some testing to see what type it is. 您将必须进行一些测试以查看其类型。

只需创建小怪列表为

List<Mob> mobs;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM