Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does AbstractCollection not implement size()?

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?

like image 522
Adam Paynter Avatar asked Jul 13 '11 09:07

Adam Paynter


1 Answers

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

like image 138
Jon Skeet Avatar answered Oct 23 '22 19:10

Jon Skeet