Download GemStone/S Programming Guide
Transcript
An Introduction to Collections GemStone Programming Guide Enumerating Collection defines several methods that enable you to loop through a collection’s elements. Because iterating or enumerating the elements of a data structure is one of the most common programming tasks, Collection’s built-in enumeration facilities are extremely useful; they relieve you of worrying about data structure size and loop indexes. And because they have been carefully tailored to each of Collection’s specialized subclasses, you needn’t create a custom iterative control structure for each enumeration problem. The most general enumeration message is do: aBlock. When you send a Collection this message, the receiver evaluates the block repeatedly, using each of its elements in turn as the block’s argument. Suppose that you made an instance of IdentitySet in this way: Example 4.4 | virtues | virtues := IdentitySet new. virtues addAll: #(’humility’ ’generosity’ ’veracity’ ’continence’ ’patience’). ((UserGlobals at: #Virtues put: virtues) sortAscending: '') verifyElementsIn: #[ 'continence', 'generosity', 'humility', 'patience', 'veracity' ] To create a single String to which each virtue has been appended, you could use the message do: aBlock like this: Example 4.5 | aString | aString := String new. "Make a new, empty String." "Append a virtue, followed by a space, to the new String" (Virtues sortAscending: '') do: [:aVirtue | aString := aString , ' ' , aVirtue]. ^ aString continence generosity humility patience veracity In this example, the method for do: executes the body of the block (aString , ’ ’ , aVirtue) repeatedly, substituting each of Virtues’ elements in turn for the 4-6 GemStone Systems, Inc. December 2001