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

Herbert König herbertkoenig at gmx.net
Tue Jan 1 15:19:02 UTC 2008


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



More information about the Beginners mailing list