2

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>)
1
  • Why don't define your list as List<Mob> mobs? You can still add objects extending Mob to that list. Commented Feb 19, 2014 at 22:38

4 Answers 4

5

You cannot add anything but null to a List specified with an upper bounded wildcard. A 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 Lists with specific subclasses, then consider making the method generic:

public static <T extends Mob> void spawnMob(T mob, List<T> mobs){
Sign up to request clarification or add additional context in comments.

Comments

1

Try with List<Mob> mobs.

2 Comments

This makes sense, but I receive this error now The method spawnMob(Mob, List<Mob>) in the type MobSpawner is not applicable for the arguments (Zombie, List<Zombie>)
Don't change the method, just change the mobs declaration
1

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.

Comments

0

Just create mobs list as

List<Mob> mobs;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.