Reputation: 293
I have a simulation with three classes: Entities
, Plants
and Animals
(plants and animals extends
entities).
I want one method to be able to sort the three arrays, the elements in the array all inherit from the same class.
Is there a way to pass all of the arrays to a method as their parent classes.
I am calling:
sortEntityArray(AnimalList);
From:
void sortEntityArray(ArrayList<Entity> ListToSort) {
boolean sorted = false;
while (sorted == false) {
sorted = true;
for (int i1 = 0; i1 < ListToSort.size() - 1; i1++) {
if (ListToSort.get(i1).PositionX < ListToSort.get(i1 + 1).PositionX) {
sorted = false;
//switch
Entity Temp = ListToSort.get(i1);
ListToSort.set(i1, ListToSort.get(i1 + 1));
ListToSort.set(i1, Temp);
}
}
}
}
When I try to pass I get this error:
The method sortEntityArray(ArrayList<Entity>) in the type World is not applicable for the arguments (ArrayList<Animal>)
Upvotes: 3
Views: 267
Reputation: 21
You could just use the java .sort function, this will work on any array.
Upvotes: 1
Reputation: 15320
Is there a way to pass all of the arrays to a method as their parent classes?
Yes, if you pass ArrayList<Entity>
you will be able to work with all 3 types since they extend
the same parent class.
I would try changing the method's signature to:
void sortEntityArray(ArrayList<? extends Entity> ListToSort)
Upvotes: 4