[Newbies] How to deep copy elements when using collectons?

Xinyu Liu liuxinyu95 at gmail.com
Wed Jan 2 04:01:01 UTC 2008

Hi, Herbert

Thank you very much. I got it. I referred to SBE(both smalltalk by example
and squeak by example :-)).

the reason why I want to copy is because I don't want the element stored in
collection to change when I modify temp var later.
and because the element has other collections as instance vars, so i am not
sure if I need deep copy.

I tried something like this:

coll add: (temp deepCopy).

...modify temp ex. temp:= MyItem new ...

temp := (coll at: 1)  deepCopy.

The above code works when there are 2 levels of  collection.

Thanks again and best regards.

On Jan 1, 2008 11:19 PM, Herbert König <herbertkoenig at gmx.net> wrote:

> Hello Xinyu,
> if you come from another programming language, a collection stores
> only pointers to objects. No chance (and no need) to copy an object
> into a collection.
> XL> Object subclass: #MyItem
> XL> instanceVariableNames: 'subItems'
> XL> classVariableNames: ''
> XL> poolDictionaries: ''
> XL> category: 'MyTest'
> XL> But I don't know how to store/get such kind of MyItem by
> XL> using collection, I think I need deep copy an element when add it
> XL> to the collection.
> No imho, see below.
> XL> I don't think the following code works.
> XL> |temp coll|
> XL> temp := MyItem new.
> XL> temp addSubItem: 'hello'; addSubItem 'world'; yourself.
> XL> coll := OrderedCollection new.
> XL> coll add: temp
> assuming subItems is initialised as:
> OrderedCollection new
> and addSubItem: is defined as:
> subItems add: anObject
> the code should work.
> XL> How can I add the deep copied element to my collection and
> XL> retrieve it later? shall I overload the #copy method?
> The main question is: why would you want to copy the element?
> Each MyItem holds to its collection of subItems and coll holds to your
> temp.
> There may be reasons you want to use a copy put usually you just put
> your objects into the collection and retrieve them with coll at:
> If you really want to store a copy you could:
> temp1 := temp deepCopy.
> coll add: temp1.
> BTW, do you know of the free Smalltalk books, Squeak by Example being
> the latest and specifically tailored to Squeak?
> XL> Best regards and thanks
> XL> -Xinyu
> Cheers
> Herbert                            mailto:herbertkoenig at gmx.net
> _______________________________________________
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
> http://lists.squeakfoundation.org/mailman/listinfo/beginners
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.squeakfoundation.org/pipermail/beginners/attachments/20080102/2aa307e5/attachment.htm

More information about the Beginners mailing list