简体   繁体   中英

Adding subclass object to superclass list

I have a method that takes a list of a super class (Specifically my class 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:

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

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. A List<? extends Mob> List<? extends Mob> could be of anything that extends Mob . It could be a List<Mafia> for all the compiler knows. You shouldn't be able to add a Zombie to a List that could be a 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:

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. Note that when you get items from the list, you will only know for certain that they are of type Mob . You will have to do some testing to see what type it is.

只需创建小怪列表为

List<Mob> mobs;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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