You are on page 1of 18

Chapter7:Collections

Collection:Whatisit? CommonCollectionClasses Bag Set Array OrderedCollection SortedCollection CollectionMessages Thenewmessage Thenew:aNumbermessage Thewith:anObjectmessage Thesizemessage Thedo:aBlockmessage Theadd:anObjectmessage Theremove:anObjectmessage Theat:aNumberput:anObjectmessage Theat:aNumbermessage TheremoveAtIndex:aNumbermessage The,aCollectionmessage Thedetect:aBlockmessage Theselect:aBlockmessage Thereject:aBlockmessage Thecollect:aBlockmessage Summaryofcollectionsandmessages SpecialCollectionClasses TheStringclass TheSymbolclass TheDictionaryclass Summary Returnto[TableofContents][MainPage][PreviousChapter][NextChapter]

Collection:Whatisit?
Collectionsareanimportantsetofclasses.Theseclassesmanagegroupsofobjectsitisalmost impossibletowriteSmalltalkcodewithoutusingacollection.Acollectionissimplyasetofelements whereeachelementisapointertoanobject.

SmalltalkhasanumberofdifferentkindsofcollectionsincludingtheBag,Set,Array, OrderedCollection,SortedCollection,String,Symbol,andDictionary.Thefollowingdiagramillustrates theclasshierarchyofthesecollectionclasses:

Mostcollectionsdonotcarewhatclassofobjecttheyaremanaging.Ifyouwanted,eachelementina collectioncouldcontainadifferentobjectfromadifferentclass.Somecollectionsarespecificaboutthe kindofobjecttheymanage.Forexample,theclassStringisacollectionthatmustcontainonly Characterobjects. Collectionsvaryinthecapabilitiestheyprovide.Somecollectionscangrowandshrinkinsizeandare usefulforgroupsofobjectsthatrequirethisbehavior.Forexample,ifeveryinstanceofCustomerwere inalist,theadditionordeletionofcustomerswouldcausethislisttoincreaseorshrink.Toimplement thislist,youwouldneedavariablesizedcollectionwhichhasthisbehavior.Withavariablesized collection,theinitialallocationcanbespecifiedorwilldefaulttosomethingappropriate.Other collectionscannotchangetheirsizeand,asaresult,oftenhaveamoreefficientmanagementscheme. Fixedsizecollectionsareappropriatewhenthenumberofelementsinagroupisknownandisstable. Acollectioncanbeeitherorderedorunordered.Anorderedcollectionhassomeorderingtothe elements.Thiscanbeasimpleindex,asinanArray,orakeyinaDictionary,orenforcedbysome internalorderingsuchassorting. Indexingallowsyoutorefertoanelementatafixedlocation.Forexample,inanarrayofthreestrings# ('red''white''blue'),youcanrequesttheelementattheindexof1.Allindexingstartsat1andgoestothe sizeofthecollection.Indexedcollectionsarealwaysorderedanddonotarbitrarilychangetheorderof elementsinthecollection.Anobjectstaysatitsassignedlocationunlessexplicitlymoved.

Collectionscanalsobeunordered.Unorderedcollectionshavenoorderingand,therefore,theelements cannotbeindexed. Somecollectionshaveadditionalfeaturessuchasnotallowingduplicatesinthecollection. Note:Itshouldnotbesurprisingthatmostcollectionsthatareindexablemanagetheirelementsas indexedinstancevariables.Thus,youwillseesupportforthenew:,at:,andat:put:messagesdiscussed inChapter4:DataOperations.

CommonCollectionClasses
Smalltalkhasseveraldifferentcommoncollectionsthathavevariationsofthebehaviorsdiscussed above.Thefollowingtableshowsthesecollectionsandtheirbehaviors:

B E H A V I O R S

COLLECTIONS Indexed Variablesize Duplicates Sorting Bag Set Array OrderedCollection SortedCollection String Symbol Dictionary
K e y :

Holds Anyobjectbutnil Anyobjectbutnil Anyobject Anyobject Anyobject Characters Characters Key+anyobject

N N Y Y Y Y Y N

Y Y N Y Y N N Y

Y N Y Y Y Y N N

N N N N Y N N N

Y=B e h a v i o rs u p p o r t e d ,N=B e h a v i o rn o ts u p p o r t e d

CollectionClassesdohaveseveralsimilarbehaviors.Theyall: representagroupofobjectscalledelements providebasicdatastructuresforprogramming replaceiterativeconstructsintraditionallanguageswiththeCollectionMessagesdo:,detect:, select:,andcollect:. supportfourcategoriesofmessagesthatwilladdnewelements,removeelements,test occurrencesofelements,andenumerateelements.

Bag
ABagisanunorderedcollectionofelementsthatareorganizedforefficientlookup.ABagactslikea

containerintowhichthingscanbeplacedandwithdrawn.Theystoretheirelementsinrandomorder andcannotbeindexed.ABagcanincreaseorshrinkandallowsduplicatesitcancontainthesame objectmultipletimes. ABagisagoodcollectiontouseifyouneedacollectionthatcanchangeinsize,buttheorderofthe objectsinthecollectionisnotimportant,anditdoesnotmatterthatthereareduplicateobjects. Forexample,aBagisagoodchoiceformanagingalistofcustomerobjects.Itdoesnotmatterinwhat ordertheseobjectsareplacedinthelist,itisnotimportanttoindexintothislist,andthelistneedsto growandshrink. Asanexample,aBagisusedfortrackingthenumberofoccurrencesofeachelement:


a B a g: =# (123333 )a s B a g . a B a gs i z e >6 a B a go c c u r r e n c e s O f :3 O u t p u t : 4

Set
ASetisidenticaltoaBagexceptthatitdoesnotallowduplicateobjects.ASetignoresanyrequestthat wouldaddaduplicatetothecollection. Forexample,youmaydecideitisimportanttochecktoensuretherearenoduplicatecustomersinthe listwheneveranewcustomerobjectisadded.InthiscaseaSetismoreappropriatethanaBag. However,ensuringthattherearenoduplicatesaddsoverheadeverytimeanobjectisaddedtothelist. Asanexample,aSetisusedfortrackinguniqueitems:
a S e t: =# (123333)a s S e t . a S e ts i z e >3 a S e to c c u r r e n c e s O f :3 O u t p u t : 1

Array
AnArrayisafixedsizecollectionofelementsthatcanbeindexedbyintegerkeysthatbeginat1 andincrease.AnArraycannotgroworshrink.TheelementsofanArraycanbeanyobject, duplicateobjectsareallowed,andelementsarestoredinrandomorder. AnArrayisusefulwhenyouknowthesizeofthecollectionandthatsizerarelychanges.For example,let'sassumeyouaredesigninganapplicationtomanageroomsinabuilding.The numberofroomsisfixedandyouwantafastwaytoindextoeachroomtocheckfor information,suchasoccupantorphonenumber.AnArrayisagoodmatchforthissituation. AnArrayisanexampleofaclassimplementedusingindexedinstancevariables.Rememberthat thenumberofindexedinstancevariablesissetatinstancecreationtime.ThatiswhyanArrayis fixedinsize.Itcannotgrowthenumberofindexedinstancevariableswithoutcreatinganew instance.

Asanexample,anArrayisanarrayof3placeswith'hi'inthefirstposition.Thisexamplealso demonstratestheindexingabilityofanArray.
a n A r r a y: =A r r a yn e w :3 a n A r r a ya t :1p u t :' h i ' a n A r r a ya t :1 O u t p u t : ' h i ' a n A r r a ya t :3 O u t p u t : n i l

OrderedCollection
AnOrderedCollectionoffersthemostcomprehensiveprotocolofanyofthecollectionclasses,and isconsequentlythe"workhorse"usedmostoftenbyprogrammers.AnOrderedCollectionisa variablesizecollectionofelementsinwhichtheuserofthecollectionspecifiesthelocationofeach element.AnOrderedCollectioncanbeindexedbyintegerkeysthatbeginat1andincrease.The elementsofanOrderedCollectioncanbeanyclassofobject.AnOrderedCollectionalsoallows duplicatedobjectsandstorestheelementsinrandomorder. Thiscollectionisheavilyusedforvariablesizeliststhatrequirecontroloverthelocationof elementsinthecollection.Forexample,anOrderedCollectionisoftenusedinuserinterfacesfor holdinginformationtobedisplayedinalistbox.Thisallowsinformationtobeaddedorremoved fromthelist.Theindexingsupportisusefulwhentheuserselectsaparticularelementinthe OrderedCollection. AnOrderedCollectiondoesnotcontainindexedinstancevariables.Itmanagesitslistofobjectsby creatingacollectionthatisindexable.AnOrderedCollectionobjectpointstothiscollectionfrom oneofitsinstancevariables.Thusitmanagesitselementsasindexedinstancevariableswithone levelofindirection.ThatiswhyanOrderedCollectioncangroworshrink. Asanexample,anOrderedCollectionofcarsisusedtostorethreecartypesanddemonstratethe abilitytoindexthesevariables:
c a r s: =O r d e r e d C o l l e c t i o nn e w . c a r sa d d :' C a d i l l a c ' c a r sa d d F i r s t :' L e x u s ' c a r sa d d L a s t :' C o r v e t t e ' c a r sd i s p l a y O u t p u t : ( ' L e x u s '' C a d i l l a c '' C o r v e t t e ' )

SortedCollection
ASortedCollectionstoresobjectsintheorderspecifiedbyablockofcodecalledthesortblock. Thesortblockisatwoargumentblockthatindicatestheorderthetwoargumentsshouldbe storedinthecollectionrelativetoeachother.Thecollectionstoresthefirstargumentaheadofthe secondargumentinthecollectionwhenthesortblockevaluatestotrue.Thesortblockcancontain multiplestatements,butitmustreturnavaluetrueorfalse. Forexample,thefollowingblockcomparestheobjectreferencedbythevariableawiththeobject referencedbythevariableb

[ : a: b|a< =b ]

" r e t u r nt r u ew h e nai sl e s st h a n o re q u a lt ob "

Theblockreturnsavaluetrueifthefirstobjectislessthanorequaltothesecondobject.This blockcausesacollectiontostoreelementsinascendingorder.Thisisthedefaultsortblockfora SortedCollection. Thiscollectionusesthesortblockwheneveranewelementisaddedtothecollection.Thefirst argumentinthesortblockalwayspointstothenewobjectandthesecondargumentinthesort blockpointstoanexistingobject.Thecollectionrunsthesortblock,iteratingsequentiallythrough allexistingobjects,untilthesortblockreturnstrueortherearenomoreexistingobjectsinthe collection. Themethodofwritingnewsortblocksis:


# ( 43521 )a s S o r t e d C o l l e c t i o n :[ : a: b|a> =b ] # (' o n e '' t w o '' t h r e e ') a s S o r t e d C o l l e c t i o n :[: x: y|x s i z e> =y s i z e ]

ASortedCollectionwouldbeagoodchoiceformaintainingacustomerlistsortedbyname. However,thisaddssignificantoverheadwheneveranewobjectisaddedtothecollection,soit shouldbeusedprudently.

CollectionMessages
Collectionshaveavarietyofmessagesformanagingthemselves.Theparagraphsbelow summarizeonlythemostcommonlyusedmessages.

new
Thenewmessageallocatesacollectionwithadefaultsize,whichvariesdependingonthetypeof thecollection.Itreturnsthenewcollection.Forexample,thefollowingstatementallocatesaBag. Displaythemessage:
B a gn e w

Thismessagecanbeinappropriateforfixedsizecollectionssinceitallocatesanemptycollection (noelements).Remember,fixedsizecollectionscannotgrow.Forexample,displaythefollowing:
| a C o l l e c t i o n | a C o l l e c t i o n: =A r r a yn e w . a C o l l e c t i o na t :1p u t :' as t r i n g ' .

new:aNumber
Thenew:messageallocatesacollectionwithasizespecifiedbytheargumentaNumber.The messagereturnsthenewcollection.

Forafixedsizecollection,theargumentspecifiesthenumberofelementsinthecollection.Display thefollowingexample:
A r r a yn e w :1 0

Thisexpressionallocatesanarraywith10elements.Asizemessagesenttothiscollectionwill returnthenumber10.Displaythefollowingexample:
( A r r a yn e w :1 0 )s i z e

Youcanindexthisarrayuptoamaximumof10.Displaythefollowingexample:
| a C o l l e c t i o n | a C o l l e c t i o n: =A r r a yn e w :1 0 . a C o l l e c t i o na t :1p u t :' s t r i n g1 ' . a C o l l e c t i o na t :1 0p u t :' s t r i n g1 0 ' . a C o l l e c t i o n

Youcannotindexoutsideofthisrange.Bothofthefollowingstatementsarenotvalidforthe aboveexample:
a C o l l e c t i o na t :0p u t :' s t r i n g0 ' . a C o l l e c t i o na t :1 1p u t :' s t r i n g1 1 ' .

Forvariablesizecollections,thenew:messageallocatesthenumberofelementsthatcanbeadded tothecollectionbeforeadditionalspaceisneeded.Thisisaperformanceissue:allocatingtoo muchspacewastesmemoryandallocatingtoolittlecausesadditionaloverheadwheneverthe collectionneedsmorememory. Avariablesizecollection,eventhoughithasspacereserved,isemptyuntilelementsareaddedto it.Displaythefollowing:


| a C o l l e c t i o n | a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w :1 0 . a C o l l e c t i o ns i z e

Thisexamplewillreturnasizeofzero,indicatingthecollectionisempty.Nowdisplaythe following:
| a C o l l e c t i o n | a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w :1 0 . a C o l l e c t i o na d d :' s t r i n g1 ' . a C o l l e c t i o ns i z e

with:anObject
Thesefourmessagescreateacollectiontoholdthespecifiedobjects: with:anObject with:anObject1with:anObject2

with:anObject1with:anObject2with:anObject3 with:anObject1with:anObject2with:anObject3with:anObject4 Thesizeofthecollectionisequaltothenumberofkeywordsinthemessage.Forexample,the messagewith:createsacollectionwithoneelementandplacesanObjectinthecollectionatthat onelocation.Themessagereturnsthenewcollection.Thismessageisvalidforeverycollection. Displaythefollowingexamples:


A r r a yw i t h : ' s t r i n g1 'w i t h : ' s t r i n g2 ' . O r d e r e d C o l l e c t i o nw i t h : 1w i t h : 2w i t h : 3w i t h : 4 .

size
Thesizemessagereturnsthenumberofelementscurrentlyinthecollection.Itissupportedbyall collections.Ifthecollectionisempty,itssizewillbezero.Thismessageisinseveraloftheprevious examples.

do:aBlock
Thedo:messageisageneraliterationthatloopsthrougheachelementinacollectionandrunsa oneargumentblockofcodespecifiedbytheaBlockargumentwitheachelementasthe argument.Thismessageisusedforsideeffectsmostly,withnointerestinthereturnedobject. Forexample,thefollowingcodewillcountthenumberofvowelsinthestring'nowisthetime' andoutputavalueof5.Displaytheexample:
" C o u n tt h en u m b e ro fv o w e l si nas t r i n g . " | v o w e l s | v o w e l: =0 . ' n o wi st h et i m e 'd o :[: e a c h| e a c hi s V o w e li f T r u e :[ v o w e l s: =v o w e l s+1 ] ]

Asanotherexample,setavariablenumberstoacollectionofnumbers.Thefollowingexample computesthesumofallthosenumbersforaresultof15.Displaytheexample:
" C o m p u t et h et o t a ls u mo fn u m b e r si nn u m b e r s . " | n u m b e r ss u m | n u m b e r s: =# ( 12345 ) . s u m: =0 . n u m b e r sd o :[: a N u m b e r|s u m: =s u m+a N u m b e r ] . s u m

ThisexamplerunstheblockofcodeforeachnumberinthecollectionwiththevariableaNumber pointingtothatnumber.Thefollowingdiagramillustratesthisiteration.

Lookatanotherexample.Thefollowingcodecountsthenumberofevennumbersinacollection. Itproducesaresultof2.Displaytheexample:
" C o u n tt h en u m b e ro fe v e nn u m b e r si nn u m b e r s . " | n u m b e r se v e n N u m s | n u m b e r s: =# ( 12345 ) . e v e n N u m s: =0 . n u m b e r sd o :[: a N u m b e r|a N u m b e re v e ni f T r u e :[ e v e n N u m s: =e v e n N u m s+1 ] ] . e v e n N u m s

Note:Numbersrecognizesamessagecalledeventhatreturnstrueifthenumberisevenand returnsfalseotherwise.

add:anObject
Theadd:messageaddsanobjectspecifiedbytheanObjectargumenttoacollection.Themessage isvalidonlyforcollectionsthatcangrowinsize.Itreturnstheobjectthatwasadded.Displaythe followingexample:
| a C o l l e c t i o n | a C o l l e c t i o n: =B a gn e w . ^ a C o l l e c t i o na d d :1

remove:anObject
Theremovemessageremovesanobjectfromacollection.Themessageisvalidonlyforcollections thatcangroworshrinkinsize.Itreturnstheobjectthatwasdeleted.Iftheobjectisnotfound, theDebuggerwindowwillbedisplayed.Displaythefollowingexample:
| a C o l l e c t i o n | a C o l l e c t i o n: =B a gn e w . a C o l l e c t i o na d d :1 . a C o l l e c t i o nr e m o v e :1 .

Acollectionfindsanobjectbyperforminganequalitycheck,notanidentitycheck.Inthe precedingexample,thefirstobjectfoundinthecollectionwithavalueof1willbetheobject removedfromthecollection.Displaythefollowingexample:

| a C o l l e c t i o n | a C o l l e c t i o n: =B a gn e w . a C o l l e c t i o na d d :1 . a C o l l e c t i o na d d :1 . a C o l l e c t i o nr e m o v e :1 . a C o l l e c t i o n

Inthisexample,thetwoelementsinthecollectionpointtoseparateinstancesofSmallInteger, eachwithavalueof1.Thismessagewillremovethefirstobjectfoundwithavalueof1.

at:aNumberput:anObject
Theat:put:messageplacesanobject,specifiedbytheanObjectargument,inthecollectionatthe indexspecifiedbytheaNumberargument.Itreturnstheobjectplacedinthecollection.This messageisvalidforcollectionsthatcanbeindexed.Displaythefollowingexample:
| a C o l l e c t i o n | a C o l l e c t i o n: =A r r a yn e w :1 0 . a C o l l e c t i o na t :5p u t :' s t r i n g5 ' . a C o l l e c t i o n

TheindexmustbeavalidnumberoraDebuggerwindowwillbedisplayed.Displaythe following:
| a C o l l e c t i o n | a C o l l e c t i o n: =A r r a yn e w :1 0 . a C o l l e c t i o na t :1 1p u t :' s t r i n g1 1 ' .

at:aNumber
Theat:messagereturnstheobjectattheindexspecifiedbytheaNumberargument.Themessage isvalidforcollectionsthatcanbeindexed.Displaythefollowing:
| a C o l l e c t i o n | a C o l l e c t i o n: =A r r a yn e w :1 0 . a C o l l e c t i o na t :5p u t :' s t r i n g5 ' . a C o l l e c t i o na t :5

removeAtIndex:aNumber
TheremoveAtIndex:messageremovestheobjectattheindexpositionspecifiedbytheaNumber argumentandreducesthecollectionbyoneelement.Thiscausesallthesucceedingelementsto shiftdownoneindexposition.Itreturnstheremovedobject. Thismessageisonlyvalidforcollectionsthatcanbeindexedandcangrowandshrinkinsize, suchasOrderedCollection.Displaythefollowingexample:
| a C o l l e c t i o n | a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w . a C o l l e c t i o na d d :' s t r i n g1 ' .

a C o l l e c t i o na d d :' s t r i n g2 ' . a C o l l e c t i o nr e m o v e A t I n d e x :1 . a C o l l e c t i o n

,aCollection
The,messagecombinestwocollectionstoformathirdcollectionbyconcatenation.Thereceiver ofthemessagemustbeacollectionthatcanbeindexed.TheargumentaCollectioncanbeany collection.Themessagereturnsanewcollectionofthesameclass.asthereceiver. Themessageisagoodwaytogrowafixedsizecollection.Forexample,createanarrayandthen addanewelementtothearray.Displaythefollowingexample:
| a C o l l e c t i o n | a C o l l e c t i o n: =A r r a yn e w :2 . a C o l l e c t i o na t :1p u t :' s t r i n g1 ' . a C o l l e c t i o na t :2p u t :' s t r i n g2 ' . a C o l l e c t i o n: =a C o l l e c t i o n ,( A r r a yw i t h :' s t r i n g3 ' ) .

detect:aBlock
ThismessagereturnsthefirstelementinthereceiverforwhichaBlockevaluatestotrue.For example,displaythefollowing:
# (471 037 )d e t e c t :[: e a c h|e a c h>7 ]

Thiswilldisplaythe10.

select:aBlock
ThismessagereturnsasubsetofthereceivercontainingallelementsforwhichaBlockevaluates totrue.Forexample,displaythefollowing:
' n o wi st h et i m e 's e l e c t :[: e a c h|e a c hi s V o w e l]

Returnsthevalue:oieie.

reject:aBlock
ThismessagereturnsasubsetofthereceivercontainingallelementsforwhichaBlockevaluates tofalse.Forexample,displaythefollowing:
' n o wi st h et i m e 'r e j e c t :[: e a c h|e a c hi s V o w e l]

Returnsthevalue:nwsthtm.

collect:aBlock

Thismessagecreatesandreturnsanewcollectionofthesamesizeandtypeasthereceiver.The elementsaretheresultofperformingaBlockoneachelementinthereceiver.Forexample, displaythefollowing:


# ( ' n o w '' i s '' t h e '' t i m e '1 2 3 )c o l l e c t :[: e a c h|e a c hi s S t r i n g]

Returnsthestring:nowisthetime.

Summaryofcollectionsandmessages
Thefollowingtablesummarizeswhatmethodseachcollectionsupports.
M E T H O D S

COLLECTIONS do: add: remove: at: at:put: removeIndex: , detect: select: reject: collect: Bag Set Array SortedCollection Dictionary String Symbol Y Y Y Y Y Y Y Y Y N Y Y Y N N Y Y N Y Y N N N N N Y Y Y Y N N N N Y Y N Y Y Y N N N Y Y N N N N N Y Y Y N Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y

OrderedCollection Y

SpecialCollections
Therearethreeothercollectionsthatareusefulbutthatdifferenoughfromtheothercollections thattheymeritaspecialdiscussion.ThethreeclassesareString,Symbol,andDictionary.

String
LogicallytheStringclassisidenticaltotheArrayclassexceptthatitcancontainonlycharacters. Forexample,thestring'John'isshowninthefollowingdiagram:

Inspectthefollowingstring:
' J o h n '

TheStringInspectorwindowopensandshowsthecontentsofthestring.Noticethestringismade upoffourelements,eachpointingtoacharacter.Closethiswindowwhenyouaredone. AStringcannotgroworshrinkinsize,butitcanbeindexed.Thus,itsupportsthemessagesat: andat:put:butdoesnotsupportthemessagesadd:orremove:.Messagesthatappeartogrowa StringobjectcreateanewStringobjectratherthangrowanexistingobject.Forexample,display thefollowingstatement:


' J o h n ' ,' D o e ' " J o i nt w os t r i n g st of o r mat h i r ds t r i n g . "

ItreturnsanewStringobject,'JohnDoe'. AStringisanexampleofaclassthatisimplementedusingindexedinstancevariablesthatcontain bytesratherthanpointers.Eachbytecontainsthecharacterstoredatthatindexedposition. However,theinterfacetoStringisstillviapointers.Thatis,Stringexpectsapointertoaninstance ofCharacterasit'sinputandreturnsapointertoaninstanceofCharacterasoutput.Inspectthe followingexample.YouwillseethataninstanceofCharacterisreturnedfromtheat:message.


' a b c 'a t :1

AStringcanreplaceanelementunlessiswascreatedusingaliteral.Displaytwostatements:
( S t r i n gw i t h :$ x )a t :1p u t :$ y . ' x 'a t :1p u t :$ y .

BothstatementscreateaStringobjectofonecharacter,oneusingthewith:messageandthe otherusingaliteral.Theat:put:messageisthensenttoeachStringobject.Thefirststatementwill supportthemessage,thesecondstatementwillcauseanerror.ClosetheDebuggerwindowwhen itisdisplayed. Stringshaveadditionalmethodsthatmakesenseforacharacterstring.Displaythefollowing examples:


' s t r i n g 't r i m B l a n k s " R e t u r nas t r i n gw i t ht h el e a d i n ga n dt r a i l i n gb l a n k sr e m o v e d . " ' F e b r u a r y3 ,1 9 9 4 ' b r e a k A t : ' , ' " R e t u r na na r r a yo ft w os t r i n g s . " ' o n et w ot h r e e 's u b S t r i n g s " R e t u r na na r r a yo fs t r i n g sf o re a c hw o r di nt h es t r i n g . "

Symbol
Symbolsareusedbyclassestodefinetheselectorsforthemethodsdefinedfortheclass.For example,ifCustomerclasshasamethodcalledname,thenthesymbolfortheselectoris#name. Symbolsarealsousedtoprovideuniquekeysindictionaries.However,atomsmightalsobeused forthis. TheSymbolclassissimilartotheStringclass,withsomeuniquedifferences.Ithasthefollowing behavior: Asymbolisareadonlyobjectonceitiscreated. Asymbolisunique.Therecannotbetwosymbolswiththesamevalue. Anonemptysymbolcanonlybecreatedusingaliteral,suchas:
| a C o l l e c t i o n | a C o l l e c t i o n: =# S y m b o l

Thismeansitdoesnotsupportthemessagesnew:,with:,with:with:,with:with:with:,and with:with:with:with:. Itdoessupportthe,(comma)messagebutreturnsanewstring,notanewsymbol.Displaythe followingexample:


# n a m e 1 ,# n a m e 2

Note:Rememberthatasymbolisprecededbythenumber,orpound,sign. Asymbolisfixedinsize.Itcannotgroworshrink.Thismeansitcannotsupportmessages suchasadd:. Asymbolisreadonlyoncecreateditcannotbechanged.ThismeansthatSymboldoesnot supportanymethodthatcouldchangeitsvalue,suchasat:put:. Tryasimpleexample.Displaythefollowing:


# n a m ea t :1p u t :$ N .

ThiswillresultinaDebuggerwindow.Closethewindowwhenitappears.

Dictionary
Adictionaryislikeasimpledatabasetable.Dictionariesareunorderedcollectionswhoseelements areaccessedbyanexplicitlyassignedexternalkey.Keysareoftenstringsorsymbols,butin principleanyobjectcanbeusedasaDictionarykey.Dictionarieskeeptrackofkey/valuepairs.

Eachkey/valuepairisaninstanceofaclasscalledAssociation.AninstanceofAssociationpoints toanobjectthatisthekeyandpointstoanobjectthatisthevalue.Anelementinadictionary containsapointertoaninstanceofAssociation.Therearenorestrictionsontheelementsstored inaDictionary.

Keysmustbeuniqueinadictionary.Notwoassociationsinadictionarycanhavekeyswiththe samevalue. Note:Keymatchingforstoringoraccessingelementsisbasedontheequalityoperation=. Consequently,keysmustbeuniquewithrespecttotheequalityoperation,thatis,twoelements cannotbeassociatedwiththesamekeynorcantwokeysbeequal.Forexample,ifaStringobject withavalueof'name'isalreadystoredasakey,anotherStringobjectwiththesamevalue cannotbeaddedasakey. Becauseofthekey/valuepairing,severalofthemethodsforDictionaryareslightlydifferentfrom themethodsforothercollections.Dictionaryalsoprovidesseveraladditionalmethodsspecificto keysandvalues. TheparagraphsbelowbrieflysummarizesomeofthecommonmessagesforDictionary. Note:Someoftheexamplesaskthatyouinspectthem,notdisplaythem.Thedisplay commandofaDictionaryobjectonlyshowsitsvalues,notitskeys.AnInspectorwindowis neededtoseeboththekeysandvalues. add:anAssociation Theadd:messageaddstheanAssociationargumenttothedictionary.Itreturnstheassociation thatwasadded.Inspectthefollowingexample:
D i c t i o n a r yn e w a d d :( A s s o c i a t i o nk e y :' 2 5 7 5 1 1 ' ) ; y o u r s e l f

removeKey:aKey TheremoveKey:messageremovestheassociationfromtheDictionarywiththekeyequaltoaKey argument.Itreturnsthevalueoftheassociationthatwasremoved.ItdisplaysaDebugger windowifaKeycannotbefoundintheDictionary.Inspectthefollowingexample:


| a D i c t i o n a r y | a D i c t i o n a r y: =D i c t i o n a r yn e w .

a D i c t i o n a r ya d d :( A s s o c i a t i o nk e y :' 2 7 5 1 1 'v a l u e :' C a r y ,N C ' ) . a D i c t i o n a r yr e m o v e K e y :' 2 7 5 1 1 '

at:aKey Theat:messagereturnsthevalueassociatedwiththeaKeyargument.ItdisplaysaDebugger windowiftheaKeyargumentcannotbefoundintheaDictionary.Displaythefollowingexample:


| a D i c t i o n a r y | a D i c t i o n a r y: =D i c t i o n a r yn e w . a D i c t i o n a r ya d d :( A s s o c i a t i o nk e y : ' 2 7 5 1 1 'v a l u e : ' C a r y ,N C ' ) . a D i c t i o n a r ya t : ' 2 7 5 1 1 '

keyAtValue:aValue ThekeyAtValue:messagereturnsthekeyforthefirstvaluethatitfindsequaltotheaValue argument.ItdisplaysaDebuggerwindowifaValuecannotbefoundintheaDictionary.Display thefollowingexample:


| a D i c t i o n a r y | a D i c t i o n a r y: =D i c t i o n a r yn e w . a D i c t i o n a r ya d d :( A s s o c i a t i o nk e y : ' 2 7 5 1 1 ' v a l u e : ' C a r y ' ) . a D i c t i o n a r yk e y A t V a l u e : ' C a r y '

at:aKeyput:aValue Theat:put:messagefindstheaKeyintheaDictionaryandsetsitsvalueequaltotheaValue argument.Ifthekeyisnotfound,itaddsittothedictionary.Thismessagecanbeusedinsteadof theadd:messagetoaddanewassociationtothedictionary.ItreturnsaValue.Displaythe followingexample:


| a D i c t i o n a r y | a D i c t i o n a r y: =D i c t i o n a r yn e w . a D i c t i o n a r ya d d :( A s s o c i a t i o nk e y : ' 2 7 5 1 1 ' v a l u e : ' C a r y ' ) . a D i c t i o n a r ya t : ' 2 7 5 1 1 ' p u t : ' R a l e i g h ' . a D i c t i o n a r ya t : ' 4 9 2 5 5 ' p u t : ' M o n t g o m e r y ' . a D i c t i o n a r y

Noticethatthevalueforthekey'27511'hasbeenchangedandanewassociationwithakeyof '49255'andavalueof'Montgomery'hasbeenadded. do:aBlock Thedo:messageiteratesthroughalltheobjectsinthedictionaryelements,runningaone argumentblockofcodespecifiedbytheaBlockargumentwiththeargumentsettothevalueof eachassociation.Displaythefollowingexample:


| a D i c t i o n a r ya C o l l e c t i o n | a D i c t i o n a r y: =D i c t i o n a r yn e w . a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w . a D i c t i o n a r ya t : ' 2 7 5 1 1 ' p u t : ' C a r y ' . a D i c t i o n a r ya t : ' 4 9 2 5 5 ' p u t : ' M o n t g o m e r y ' . a D i c t i o n a r yd o : [ : c i t y | a C o l l e c t i o na d d : ' c i t y=' , c i t y ] .

a C o l l e c t i o n

ThisexamplereturnsanOrderedCollectionwitheachelementpointingtoaStringobjectwiththe nameofacityprecededbythecharacters'city='. keysDo:aBlock ThekeysDo:messageiteratesthroughalltheDictionaryelements,runningaoneargumentblock ofcodespecifiedbytheaBlockargumentwiththeargumentsettothekeyofeachassociation. Displaythefollowingexample:


| a D i c t i o n a r ya C o l l e c t i o n | a D i c t i o n a r y: =D i c t i o n a r yn e w . a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w . a D i c t i o n a r ya t : ' 2 7 5 1 1 ' p u t : ' C a r y ' . a D i c t i o n a r ya t : ' 4 9 2 5 5 ' p u t : ' M o n t g o m e r y ' . a D i c t i o n a r yk e y s D o : [ : z i p | a C o l l e c t i o na d d : ' z i pc o d e=' , z i p ] . a C o l l e c t i o n

ThiscreatesanOrderedCollectionwitheachelementpointingtoaStringobjectwithazipcode precededbythecharacters'zipcode='. keys Thekeysmessagereturnsasetofallthekeysinthedictionary.Displaythefollowingexample:


| a D i c t i o n a r y | a D i c t i o n a r y: =D i c t i o n a r yn e w . a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w . a D i c t i o n a r ya t : ' 2 7 5 1 1 ' p u t : ' C a r y ' . a D i c t i o n a r ya t : ' 4 9 2 5 5 ' p u t : ' M o n t g o m e r y ' . a D i c t i o n a r yk e y s

values ThevaluesmessagereturnsaninstanceoftheclassBagofallthevaluesintheDictionary.Display thefollowingexample:


| a D i c t i o n a r y | a D i c t i o n a r y: =D i c t i o n a r yn e w . a C o l l e c t i o n: =O r d e r e d C o l l e c t i o nn e w . a D i c t i o n a r ya t : ' 2 7 5 1 1 ' p u t : ' C a r y ' . a D i c t i o n a r ya t : ' 4 9 2 5 5 ' p u t : ' M o n t g o m e r y ' . a D i c t i o n a r yv a l u e s

Note:WhydoesDictionaryreturnkeysinaSetandvaluesinaBag?ASetdoesnotallow duplicateswhereasaBagdoes.ADictionaryobjectcannothaveduplicatekeys,soaSetisagood match.ButbecauseaDictionaryobjectcanhaveduplicatevalues,theyareplacedinaBag.

Summary

Let'sreviewsomeoftheimportantpointscoveredinthischapter: Collectionsmanageagroupofobjects. ABagisavariablesizedcollectionthatstoresobjectsinrandomorderandisnotindexable. ASetisidenticaltoaBagexceptitdoesnotallowduplicateobjects. AnArrayisafixedsizecollectionthatisindexable. AnOrderedCollectionisavariablesizecollectionthatisindexable. ASortedCollectionisavariablesizecollectionthatstoresobjectsintheorderspecifiedbya twoargumentsortblock. Collectionshaveseveralmessagesthatsupportthemanagementofacollection.This includescreatingnewcollections,queryingthesizeofacollection,addingobjectstoa collection,removingitemsfromacollection,anditeratingthroughacollection. AStringissimilartoanArrayexceptthatiscancontainonlycharacters. ASymbolissimilartoaStringexceptthatitdoesnotallowduplicateSymbolobjectswith thesamevalue. ADictionarymanageskey/valuepairs.ADictionaryhasseveralmessagesthatsupportthe managementofaDictionary. Returnto[Topofthepage] SmalltalkTutorial GotoChapter8:Streams ReturntoChapter6:Inheritance ReturntoMainPage

You might also like