December 21, 2024

The Protocol of Dictionary

 

accessing size , at: , at:ifAbsent: , at:put:
adding add:
removing removeKey: , removeKey:ifAbsent:
testing includes: , includesKey: , isEmpty
enumerating do:

On the previous page I used the add: selector to make the dictionary but I could have used at:put:

fbaconDictionary := Dictionary new.
fbaconDictionary at: '4689' put: 'Meat Rack';
                 at: '5005' put: 'George smoking';
                 at: '4767' put: 'Man with a drink';
                 at: '5313' put: 'Another man with a drink'

If you try to add an association with a key that already exists then the value corresponding to that key is updated. For example:

fbaconDictionary at: '4767' put: 'Screaming Pope'

This updates the existing association but does not add a new association to the dictionary. Any reference to the string 'Man with a drink' is removed. The message answer is the second argument 'Screaming Pope'.
If an association is in the dictionary, at: can be used to retrieve the value associated with the key.

fbaconDictionary at: '5005'

This returns 'George smoking'
Again we can guard against error by use of at:ifAbsent:

fbaconDictionary at: '5004' ifAbsent: [Dialog warn: 'This stock number is absent']

The size message returns the number of Association instances held in the dictionary

fbaconDictionary size

answers 4

Removing associations involves the use of the removeKey: or removeKey:ifAbsent: selectors.

fbaconDictionary removeKey: '4767'

This removes the association with the key supplied in the argument and answers with the corresponding value, in this case 'Screaming Pope'.
Once again the removeKey:ifAbsent: avoids the potential for errors.

The includesKey: results in all the keys in the dictionary being tested against the argument with the = message selector and true or false are returned. This has implications for the class of object used as the key. As already mentioned the use of symbols as keys leads to a speedier searching process.

Finally the do: selector is used to iterate over all the associations in the dictionary.

fbaconDictionary do: [: each | Dialog warn: 'Title: ', each ]

It is important to remember when iterating through a dictionary with do: , that the block argument, in this example each, references the value of each association in the dictionary and not the key. In this case a succession of dialogue boxes opens and identifies the title of each work.

Next page » Array

Previous page « Dictionary

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page