[Newbies] How to empty a collection?

Igor Stasenko siguctua at gmail.com
Tue Feb 19 10:47:46 UTC 2008


On 19/02/2008, goran at krampe.se <goran at krampe.se> wrote:
>
> 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.
>

Hmm, what would you put in Array>>removeAll: or Interval>>removeAll: ?
Arrays don't have ways to change a number of elements they contain.
All you can do is to make a copy of it with changed collection of
elements during copy, but that would be another array, not original
one.
Oh, but yes, there already different #removeXXX methods in Collection
class. This method will have same problems with Array/Interval as this
ones.

A most 'pragmatic' change in this way would be to insert a subclass of
Collection like DynamicCollection and move all methods which may
affect the number of elements to this class. Then all collection
types, which can dynamically change the number of elements should
subclass from it.
But we are all know, that such changes will never appear regardless
how much pragmatic they are. ;)


> regards, Göran
>


-- 
Best regards,
Igor Stasenko AKA sig.


More information about the Squeak-dev mailing list