在这种情况下,可以替代instanceof方法

Jax*_*Jax 5 java instanceof

您好,我想知道有什么比这更优雅的替代品:

class Base...

class A extends Base...

class B extends Base...

//iterator of colection containing mixed As and Bs i want to remowe Bs and do omething with As
while(iterator.hasNext()) {
    Base next = iterator.next();
    if(next instanceof A) // do something
    if(next instanceof B)
        iterator.remove();
}
Run Code Online (Sandbox Code Playgroud)

播种替代品...

谢谢你的建议。

编辑:基类可能有许多子类,而不仅仅是两个,它们的数量可能会随着时间增长

Ser*_*kov 0

我认为这是非常简短且清晰的解决方案,并且没有其他选择(无需代码增长),只需添加else if而不是if在第二种情况下

您还可以在函数调用上拆分代码,并且 if 语句不会很大

另一个解决方案是创建Map将被调用的委托。像这样: interface ISimpleDelegate{ void doSomeLogic(Base b) } `Map delegates = new HashMap();

之后将您的逻辑添加为实现 ISimpleDelegate 的匿名类。 delegates.put(A.class, new ISimpleDelegate() { //write your logic here });

我希望这个想法很清楚

在你的循环中你只需调用代表:

while(iterator.hasNext()) {
    Base next = iterator.next();
    delegates.get(next.getClass()).doSomeLogic(next);
}
Run Code Online (Sandbox Code Playgroud)