Why does AbstractCollection not implement size()?

2019-06-21 06:04发布

When sub-classing AbstractCollection, I must still implement size(), even though (I believe) there is a reasonable correct (though non-performant) default implementation:

public int size() {
    int count = 0;

    for (Iterator<E> i = iterator(); i.hasNext();) {
        i.next();
        count++
    }

    return count;
}

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?

5条回答
淡お忘
2楼-- · 2019-06-21 06:21

While this is a possible default implementation, it is not necessarily a good one (or even a sane one).

In almost all general-purpose Collection implementation there's a O(1) way to find out the size. Usually by simply querying a simple field.

This should be the implementation. In the very rare cases where this is not the case, the implementation could still fall back to your example code (or implement it differently).

查看更多
Deceive 欺骗
3楼-- · 2019-06-21 06:22

Actually, since both the add and remove operations have a return value that indicates whether the operation resulted in a change of the size of the collection, you could implement an event better size method by keeping track of adds and removes in most cases.

查看更多
对你真心纯属浪费
4楼-- · 2019-06-21 06:23

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 :)

查看更多
Fickle 薄情
5楼-- · 2019-06-21 06:33

I support your theory: maybe implementers are just forced to implement a good (O(1) if possible) implementation for size(), because

  • the method is used quite often
  • if we program against interfaces, we don't know the actual collection type
  • A default (or bad) implementation may kill performance unexpectedly
查看更多
别忘想泡老子
6楼-- · 2019-06-21 06:33

For some kinds of list, your proposed default implementation is harmful. I'm thinking of lazy lists, or lists that result in a very large in-memory data structure when iterated.

In the infinite lazy list case, your proposed default implementation is plainly incorrect.

查看更多
登录 后发表回答