Siddharth Thakur
Siddharth Thakur

Reputation: 13

method adding objects extending abstract class to Arraylist of type Abstract Class in java

I'm having some trouble creating a method to add objects which extend an abstract class(Ant_Abstract) to an ArrayList of type objects extending Ant_Abstract. So far I have two kinds of ants, Scouts and Workers(both extending Ant_Abstract), and I want to use an ArrayList to contain both kinds of Ants in the file Anthill.

When I try to compile:

import java.util.*;
class Anthill{
     public ArrayList<? extends Ant_Abstract> occupants=new ArrayList(15);
     Anthill(){
     }
     public<t extends Ant_Abstract> void enter(Class<t> ant){
            occupants.add(ant);
     }
}

it gives me the error: "The method add(capture#1-of ? extends Ant_Abstract) in the type ArrayList is not applicable for the arguments (Class)

Please help.

Upvotes: 1

Views: 903

Answers (1)

pczeus
pczeus

Reputation: 7867

In order to use the 'T' as a generic type, you need to indicate this at the class declaration. Then within properties and methods on your class Anthill, you can then reference it throughout:

public class Anthill<T extends Ant_Abstract>{
     public ArrayList<T> occupants = new ArrayList<>(15);

     public void enter(T ant){
            occupants.add(ant);
     }
}

You need to change the declaration of your ArrayList to this:

     public ArrayList<T> occupants = new ArrayList<>(15);

Change Class<T> to just T

You are not trying to add the Class (which is an object type in itself). Your intention is to add an instance of Abstract_Ant implementation, not the Class itself.

Take a moment to read over the Java Generics Lesson

Upvotes: 2

Related Questions