[Newbies] How to empty a collection?
goran at krampe.se
goran at krampe.se
Tue Feb 19 09:23:20 UTC 2008
Hi!
CCing squeak-dev because I would like to see this fixed. :)
"Ron Teitelbaum" <Ron at USMedRec.com> wrote:
> Hi Sophie,
>
> aCollection copy do: [:anElement |
> aCollection remove: anElement
> ].
>
> Why copy? If you start removing items from the collection, increasing the
> index will cause you to skip elements.
Because modifying the collection while iterating over the same is not
safe generally. The above idiom is "known" - but of course it sucks. :)
I advocated to add a #removeAll message in the protocol of Collection
and then implement it in subclasses using efficient variants a looooong
while back but it never got accepted. The climate today for such a
change is much more... "pragmatic" I think and hope. So we should simply
add it!
The *normal* way people usually do it thoiugh is to *not depend on the
identity* of the Collection - different objects should typically not
share the same Collection. And if you don't share - then the easy way
out is to just do:
myCollection := OrderedCollection new "or whatever class you use"
...in order to empty it.
But in low level code it would be nice to have the #removeAll method
because it can be very efficiently implemented in different subclasses
and would avoid reallocations etc.
regards, Göran
More information about the Squeak-dev
mailing list
|