I'm making a tankgame. In my PlayPanel
class I wrote this code, as you can see it is mostly the same but it's used for 3 different ArrayList
s.
I would really like to know how to write this method once only in order to reuse it for all the ArrayList
s because it seems so untidy.
//obstacles
for (int i = 0 ; i<obstacles.size() ; i++) {
if (obstacles.get(i).dood)
obstacles.remove(i);
}
//bullets
for (int i = 0; i< bullets.size(); i++) {
bullets.get(i).redraw();
//de positie van elke kogel wordt geupdate.
if(bullets.get(i).OutOfScreen()) {
bullets.remove(i);//uit scherm -> verwijdert en verplaatst
}
}
for (int i = 0; i< enemyBullets.size(); i++) {
enemyBullets.get(i).redraw();
if(enemyBullets.get(i).OutOfScreen()) {
enemyBullets.remove(i);
}
}
I thought about writing this, but it doesn't seem right:
public void remove(ArrayList object) {
for (int i = 0; i< object.size(); i++) {
object.get(i).redraw();
if(object.get(i).OutOfScreen()) {
object.remove(i);
}
}
}
Also, I don't really know how to call this method to use it for one of the ArrayList
s.
The second and third loop can be combined in a single piece of code as shown as follows.
Now via Polymorphism you can do the following
Now you can have bullets and enemybullets as a collection is an ArrayList and you can call the above method like:
loop(bullets); or loop(enemyBullets);
Your method
remove
won't work, since you are giving as an argument anArrayList
ofObject
s. They don't have methodsredraw
andOutOfScreen
. What you could do is define an interface, sayGameObject
, containing these methods, and makeBullet
implement it. Change signature ofremove
toThen you can call for example
remove(bullets)
orremove(enemyBullets)
.If you use Java 8, you can filter the list with by passing a
Predicate
.Here's an example of how to use method above for
List<Bullet>
:The benefit of using this approach is that you don't need class inheritance or something like that.