您好我想知道这样的更优雅的替代方案是什么:
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();
}
播种有哪些替代品……
谢谢你的建议.
编辑:基类可能有许多子类,而不仅仅是两个,它们的数字可能会及时增长
最佳答案 您可以在Base中创建方法并在A和B中覆盖它们.
例如:
class Base{
public boolean shouldRemove(){
return false;
}
public void doSomething(){
}
}
class A extends Base{
@Override
public void doSomething() {
}
}
class B extends Base{
@Override
public boolean shouldRemove() {
return true;
}
}
然后你不需要知道对象是一个实例的类:
while(iterator.hasNext()) {
Base next = iterator.next();
if(next.shouldRemove()){
iterator.remove();
}
else{
next.doSomething();
}
}