www.delorie.com/gnu/docs/smalltalk/gst_51.html   search  
Buy GNU books!

GNU Smalltalk User's Guide

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.2.3 Dictionaries

A dictionary is a special kind of collection. With a regular array, you must index it with integers. With dictionaries, you can index it with any object at all. Dictionaries thus provide a very powerful way of correlating one piece of information to another. Their only downside is that they are somewhat less efficient than simple arrays. Try the following:
   x := Dictionary new.
   x at: 'One' put: 1 !
   x at: 'Two' put: 2 !
   x at: 1 put: 'One' !
   x at: 2 put: 'Two' !

This fills our dictionary in with some data. The data is actually stored in pairs of key and value (the key is what you give to at:---it specifies a slot; the value is what is actually stored at that slot). Notice how we were able to specify not only integers but also strings as both the key and the value. In fact, we can use any kind of object we want as either--the dictionary doesn't care.

Now we can map each key to a value:
   (x at: 1) printNl !
   (x at: 'Two') printNl !

which prints respectively:

We can also ask a dictionary to print itself:
   x printNl !

which prints:
   Dictionary (1->'One' 2->'Two' 'One'->1 'Two'->2 )

where the first member of each pair is the key, and the second the value.

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003