Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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.
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 :
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
Bag
ABagisanunorderedcollectionofelementsthatareorganizedforefficientlookup.ABagactslikea
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 ]
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 ' .
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
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 .
| 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
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 '
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 .
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
ThiswillresultinaDebuggerwindow.Closethewindowwhenitappears.
Dictionary
Adictionaryislikeasimpledatabasetable.Dictionariesareunorderedcollectionswhoseelements areaccessedbyanexplicitlyassignedexternalkey.Keysareoftenstringsorsymbols,butin principleanyobjectcanbeusedasaDictionarykey.Dictionarieskeeptrackofkey/valuepairs.
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
a C o l l e c t i o n
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