Convert ArrayList<subclass> to ArrayList<superclass>
java
Solution
The fundamental issue you are facing is that `List<Subclass>` is not a subtype of `List<Superclass>`.
The way to solve your problem is to declare the variable using a generic bound:
List<? extends Organism> search;
then this will compile:
search = foods;
The declaration `List<? extends Organism>` means "A List of an unknown type that is a subtype of Organism". In code, elements of such a list are known to at least be an Organism, but the exact type is unknown.
Problem
I have three classes: Blob, Food and Predator, all of which are subclasses of the abstract class Organism. I also have an ArrayList for each class: blobs, foods and predators I'm writing a function that will choose a 'target' for an organism depending on what type it is. The organism is passed as a parameter and then an appropriate target is chosen - if a Blob is passed then it should target a Food, if a Predator is passed then it should target a Blob, and if a Food is passed then it should target a Predator. Right now I have: ``` ArrayList<Food> foods = new ArrayList<Food>(); ArrayList<Blob> blobs = new ArrayList<Blob>(); ArrayList<Predator> predators = new ArrayList<Predator>(); public Organism pickTarget(Organism o){ ArrayList<Organism> search = new ArrayList<Organism>(); if(o.getClass() == Blob.class){ search = foods; } else if(o.getClass() == Predator.class){ search = blobs; } else if(o.getClass() == Food.class){ search = predators; } Organism target = search.get(0); for(Organism organism:search){ //do stuff to pick a target from assigned search space } return target; } ``` So the idea here is to intialise a generic Organisms ArrayList, then assign one of the existing ArrayLists to it depending on what type the parameter is. That ArrayList will then be searched for the most suitable target which is returned. But I'm getting a type mismatch error when I try to assign an existing ArrayList to the search variable. 'Cannot convert from `ArrayList<Food>` to `ArrayList<Organism>` ', for example. Does anybody know of a solution to a problem like this? Converting from a subclass to a superclass isn't usually an issue so I'm hoping that there is a solution for ArrayLists.