gpt4 book ai didi

java - 抽象 ArrayList 迭代以构建可重用的方法

转载 作者:行者123 更新时间:2023-12-01 23:12:08 25 4
gpt4 key购买 nike

目前我的代码可以工作但重复:

Iterator<Moo> it6 = moos.iterator();
while (it6.hasNext()) {
Moo m = it6.next();
m.update();
if (!m.isActive())
it6.remove();
}

Iterator<Pip> it7 = pips.iterator();
while (it7.hasNext()) {
Pip s = it7.next();
s.update();
if (!s.isActive())
it7.remove();
}

... and other ...

在该类上定义 pips 和 moos 的位置:

public class GameEngine {
private ArrayList<Moo> moos;
private ArrayList<Pip> pips;
...

Moo/Pip 类喜欢:

public class Moo extends GameSprite {
...

public class Pip extends GameSprite {
...

我可以使用一些设计模式(或一些不同的实现)来减少编写的代码并使其更加优雅吗?

最佳答案

如果您在 GameSprite 中声明 isActive()update(),则可以使用通用方法:

private static void update(List<? extends GameSprite> sprites) {

Iterator<? extends GameSprite> it = sprites.iterator();
while (it.hasNext()) {
GameSprite s = it.next();
s.update();
if (!s.isActive())
it.remove();
}
}

然后只需调用它即可

update(pips);
update(moos);

关于java - 抽象 ArrayList<E> 迭代以构建可重用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21783370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com