10

I'm still pretty new to Java, so I might be missing something obvious here.

I have the following code that I use to pick class types from a list of all my entities:

public Array<?> PickEntities(Class<?> cls) { Array<? super SpriteEntity> allEntities = new Array<Object>(); for (SpriteEntity entity : MyGame.AllEntities) { if (entity.getClass() == cls) { allEntities.add(entity); } } return allEntities; } 

That works fine, but it means that when calling this method I still need to cast it to the class on the other side. For example:

asteroid = (Asteroid)PickEntities(Asteroid.class); 

What I would like to do is use the class I am passing to my PickEntities class (the cls parameter) and then cast the returning array (allEntities) to that type.

Is there a way to do this? Whenever I try it just tells me that 'cls' is not a type and can't be used to cast.

1
  • Where is the class Array defined? Commented May 18, 2013 at 14:57

1 Answer 1

15

Your method should be generic:

public <T extends SpriteEntity> List<T> pickEntities(Class<T> clazz) { List<T> result = new ArrayList<T>(); for (SpriteEntity entity : MyGame.allEntities) { if (entity.getClass() == clazz) { result.add((T) entity); } } return result; } 

Note that I used standard collection classes, and standard Java naming conventions.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, that's some awesome code! Works perfectly, and I got a lesson in how to better use Java :D Thanks mate!
Note that the above code, like the code from the OP, will only include instances where the class is exactly the same as clazz; it won't include subclasses. Also, you can avoid the cast by calling clazz.cast(entity)
If you want to include subclasses, you can use this code: if (clazz.isInstance(entity)) result.add(clazz.cast(entity));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.