2014-02-19 43 views
2

我有一个方法,需要一个超类(特别是我的类Mob)的列表。它看起来像这样:将子类对象添加到超类列表

List<? extends Mob> mobs 

我希望能够加入扩展了超类的群氓到这个列表中的任何对象,像这样:

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

如果是这种问题的方法:

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

这行代码World.getInstance().getZombies()返回对象Zombie的列表。僵尸延伸暴民。

然而,这行代码:

mobs.add(mob); 

抛出这个错误:

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

我能做些什么来解决这个问题?

编辑,改变以除外List<Mob>的方法后,我收到此错误:

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

为什么不定义你的列表,列表' mobs'?您仍然可以将扩展Mob的对象添加到该列表中。 – exception1

回答

2

您不能添加除null之外的任何内容到由上限制通配符指定的List。 A List<? extends Mob>可以是延伸Mob的任何东西。它可能是一个List<Mafia>所有编译器知道。您应该无法将Zombie添加到List,这可能是List<Mafia>。为了保持类型安全,编译器必须阻止这种调用。

要添加到这样的列表,您必须删除通配符。

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

如果你可能在List s的具体子类来传递,然后再考虑使得该方法一般:

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

尝试用List<Mob> mobs

+0

这是有道理的,但我现在收到这个错误'MobSpawner类型中的方法spawnMob(Mob,List )不适用于参数(Zombie,List )' – user3316633

+0

不要更改方法,只需更改' '怪物''声明 –

1

你可以只申报表作为List<Mob> mobs,以及Mob任何子类会公认。请注意,当您从列表中获取项目时,只能确定它们属于Mob类型。你将不得不做一些测试,看看它是什么类型。

0

只需创建小怪列表,

List<Mob> mobs; 
相关问题