|
Primer : Collections (Sets) (Part 1) |
|
|
The Collection class (and all its sub-classes) is one feature of the Smalltalk
language that makes it so powerful. Tedious lines of code that are written over
and over again in other languages are just a single message in Smalltalk.
|
||
|
This primer introduces Sets and describes some of their specific characteristics.
|
||
|
1.
If VisualWorks is not already running, please start running it now.
2. Open a Workspace. From the VisualWorks main Launcher window, either click the last button on the Toolbar or select the menu option Tools>>Workspace. 3. In the Workspace, enter the following:
| mySet |
Note that a new (Inspector) window will appear and the caption of the window is
a Set.
mySet := Set new. mySet add: 'dog'. mySet add: 'cat'. mySet add: 'dog'. mySet inspect. 4. In the left pane of the Inspector window, click (highlight) the word self. You should see Set ('dog' 'cat') 5. In the left pane of the Inspector window, select the Basic tab and click (highlight) the word tally. You should see 2
6. Close the Inspector window |
||
|
How does a Set (Collection) work?
By definition, a "set" is a group of things connected by or collected for something that they all have in common (i.e something similar about the group). In this case, it is a group of animals. However, a Smalltalk set only contains unique items that are added to it. On the first line of our example, we declare a temporary variable (mySet). On the second line, we tell Smalltalk to create a new Set and assign it to our temporary variable. On the third line, we add the String 'dog' to our set. On the next line, we add the String 'cat' to our set. On the next line, we add the String 'dog' to our set. Then we tell Smalltalk to inspect our set. When we execute the code to add 'dog' for the second time, Smalltalk looks inside the set, determines that 'dog' is already there, and basically does nothing - it is already there (so why add it again?). In most programming languages, you would have to write this code yourself. In Smalltalk, it's built into the language. | ||
|
SummarySets are collections of unique items. Although there are many methods associated with sets, at this time we are only concerned about how to add items to a set and count the number of items in a set. |