你好,我想知道像这样的东西有什么更优雅的替代品:
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
and 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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)