如何重写这3种方法以使其可重用? [英] How to rewrite these 3 methods to be reusable?
问题描述
我正在制作坦克游戏.在我的 PlayPanel
类中,我编写了这段代码,正如您所看到的,它几乎相同,但用于 3 个不同的 ArrayList
.
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.
我真的很想知道如何只编写一次这个方法,以便在所有 ArrayList
中重复使用它,因为它看起来很不整洁.
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);
}
}
}
此外,我真的不知道如何调用此方法以将其用于 ArrayList
之一.
Also, I don't really know how to call this method to use it for one of the ArrayList
s.
推荐答案
如果您使用 Java 8,您可以通过传递一个 Predicate
.
If you use Java 8, you can filter the list with by passing a Predicate
.
public class Helper {
//removePredicate can be any function that returns a boolean that will help
//to filter the data
static <T> void remove(List<T> list, Predicate<? super T> removePredicate) {
List<T> filteredList = list.stream()
.filter(removePredicate)
.collect(Collectors.toList());
list.clear();
list.addAll(filteredList);
}
}
以下是如何将上述方法用于 List
的示例:
Here's an example of how to use method above for List<Bullet>
:
//sample implementation for Bullet class
class Bullet {
int value;
public Bullet(int value) { this.value = value; }
public boolean outOfScreen() {
return value > 10;
}
@Override public String toString() {
return String.format("Bullet: {%d}", value);
}
}
//somewhere you need to execute this code...
//initialize your List
List<Bullet> bulletList = new ArrayList<>(Arrays.asList(
new Bullet(15), new Bullet(1), new Bullet(20), new Bullet(6)));
//show the contents of the list
System.out.println(bulletList);
//remove the elements by using whatever you want/need
//see how you can pass any way to filter the elements of the list
Helper.remove(bulletList, b -> !b.outOfScreen());
//show the contents of the list again to show how it was filtered
System.out.println(bulletList);
使用这种方法的好处是您不需要类继承或类似的东西.
The benefit of using this approach is that you don't need class inheritance or something like that.
这篇关于如何重写这3种方法以使其可重用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!