I’m trying to write a method to return all objects that match the class it gets as a parameter:
public class Scenario extends View {
...
private Actor[] actors = new Actor[1024];
...
public Actor[] getActors(Class<?> cls) {
//Count actors corresponding to class cls
int cnt = 0;
for (int i = 0; i<actorsCount; i++)
if (actors[i] instanceof cls) cnt++;
//Build a new array;
Actor[] clsActors = new Actor[cnt];
//Fill it
for (int j = 0, k=0; j<cnt; k++)
if (actors[k] instanceof cls)
clsActors[j++] = actors[k];
return clsActors;
}
}
However, I’m getting an error: “- Incompatible operand types boolean and Class<capture#1-of ? extends Scenario>”
‘Actor’ is extended by my sprites, say Bird, Hero, etc.
The idea is, for example, to get a list of all Birds on the Scenario at a given time for some calculations.
Any idea what’s going on here? How to test if a given object is an instance of a given class?
Output:
Edit: More elegant version of getActors() using a List: