Why does AbstractCollection not implement size ()?

In the subclassification, AbstractCollectionI still have to implement it size(), although (I suppose) there is a correct (albeit inefficient) default implementation that is reasonable :

public int size() {
    int count = 0;

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

    return count;
}

Why didn't designers include a standard implementation size()? Were they trying to get developers to consciously think about this method, hoping that the developer would suggest an implementation that works better than the default?

+5
source share
5 answers

, - . . , , . , , , , () . :)

+11

, ( ).

Collection O (1) . .

. , , ( -).

+5

: , (O(1) ) size(),

  • ,
  • ( )
+1

. , .

In the case of an infinite lazy list, your proposed default implementation is clearly incorrect.

+1
source

In fact, since the operation addand removehave a return value that indicates whether the operation has led to a change in the size of the collection, you could implement a better method size, tracking adds and removes most of the time.

0
source

All Articles