There is a method that installs an adapter and writes a dataset to it. There are 4 types of data extending SuperClass. In order to initialize the adapter, I use 4 methods (1 for each data set):

setTypeDogAsAdapter(); setTypeCatAsAdapter(); 

... etc.

 setTypeDogAsAdapter(){ final ArrayList<Dog> dogs = new ArrayList<>(); petAdapter = new PetListAdapter(this, groups); petAdapter .notifyDataSetChanged(); for (Dog dog: petService.getPetItemListHolder().getItems()) { dogs .add(dog); } ... } 

And so 4 times.

I want to do something like

 setPetsAdapter(Dog); setPetsAdapter(Cat); 

etc.

 final ArrayList<<? extends Pet>> dogs = new ArrayList<>(); petAdapter = new PetListAdapter(this, groups); petAdapter .notifyDataSetChanged(); for (... ... : petService.getPetItemListHolder().getItems()) { ... .add(...); } 

    1 answer 1

    Your task is solved by passing to the generic method of the class, by which the method must be parameterized:

     public <T> void setPetsAdapter(Class<T> clazz) { List<T> pets = new ArrayList<T>(); for (T pet : petService.getPetItemListHolder().getItems()) { pets.add(pet); } ... } setPetsAdapter(Dog.class); setPetsAdapter(Cat.class); 

    However, there is a problem: the petService.getPetItemListHolder() method returns ... what? List<Pet> ? In this case, the code will not compile, as there is a risk to cast Cat to Dog (if, for example, the collection returned by petService.getPetItemListHolder() contains instances of both classes, and we called the setPetsAdapter method with the Dog parameter). So the petService.getPetItemListHolder() method will also have to be parameterized to ensure that it returns a collection of objects that are compatible with the parameter of the setPetsAdapter method (I slightly simplified the example for clarity):

     public <T> List<T> getPetItemList(Class<T> clazz) { return new ArrayList<T>(); } public <T> void setPetsAdapter(Class<T> clazz) { List<T> pets = new ArrayList<T>(); for (T pet : getPetItemList(clazz)) { pets.add(pet); } ... } setPetsAdapter(Dog.class); setPetsAdapter(Cat.class); 
    • Thank! Now I understand where it was wrong and what to read. - Garf1eld