I have often wished to create a keyed collection of objects (i.e. a Dictionary) in which the elements could be accessed by key or iterated over in the order in which the elements were added (i.e. treat the collection as either a Dictionary or an OrderedCollection.)
I have seen a few implementations of dictionary classes that retain the insertion order of their elements, but they all seemed to be overly complicated to me. I created this OrderedDictionary by overriding just 5 methods of Dictionary. It remembers the insertion order by maintaining a parallel ordered collection of the associations in an instance variable.
Instances of OrderedDictionary behave as Dictionaries in all respects except that when associations, keys, or values are iterated over, the order in which the iteration occurs is the same as the order in which the associations were originally added to the OrderedDictionary instance.
OrderedDictionary is in Squeaksource
Comments
Hi Tony,
I often just create it on the fly like this:
Now you can iterate myOrderedDictionary, as it is an OrderedCollection, but you can also ask it for keys and values:
It's not strictly a dictionary, but it will work for most of the cases.
Cheers!
Bernat.
Oops Pier messed my code up :(
http://pastie.org/1565960
I cleaned up the comment code.
(A missing feature of Pier is the ability of reviewing a formatted version of your comment before committing it -- or being able to edit one's comment after committing it.) For future reference, I have installed the plug-in that allows you to format Smalltalk code by prefixing each line with ==.