问题描述
当子类化 AbstractCollection
时,我仍然必须实现 size()
When sub-classing AbstractCollection
, I must still implement size()
, even though (I believe) there is a correct (though non-performant) default implementation:
public int size() {
int count = 0;
for (Iterator<E> i = iterator(); i.hasNext();) {
i.next();
count++
}
return count;
}
为什么设计师不包括 size()
?他们试图强制开发人员有意识地考虑这种方法,希望导致开发人员提供的执行效果比默认的更好。
Why did the designers not include a default implementation of size()
? Were they trying to force developers to consciously think about this method, hopefully causing the developer to offer an implementation that performs better than the default?
推荐答案
我怀疑你的最后一句话是真正的原因。当子类化一个抽象类时,它有时是诱人的,只覆盖抽象方法。我希望几乎每个实现都有一个更好的实现比只是迭代 - 所以如果你几乎每个人都重写一个方法,这可能是一个好主意,不提供一个基(慢)实现。它只是减少了拧紧的机会:)
I suspect your last sentence is the real reason. When subclassing an abstract class it's sometimes tempting to only override the abstract methods. I would expect almost every implementation to have a better implementation than just iterating - so if you want pretty much everyone to override a method, it's probably a good idea not to provide a base (slow) implementation. It just reduces chances of screwing up :)
这篇关于为什么AbstractCollection没有实现size()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!