Typical Smalltalk Collections
To create new instances of MyClass, send the message #new to the class
MyClass new
Now, to add an item to the collection, just send the collection with the #add message:
list add: MyClass new
Smalltalk doesn't have such things as static types. In other words, the Java equivalent of ArrayList <MyClass> is simply OrderedCollection.
source to share
Before answering this, it is important to emphasize that there is no strong typing in Smalltalk. Each variable is an instance of some object class. But the class of an object can change frequently during the lifecycle of the object, and neither the interpreter nor the compiler will care.
Enter the following code into the workspace (or "Playground" on Pharo 4.0 and above, or on the command line in GNU Smalltalk)
aNumber := 3 . "new instance of Class SmallInt is created"
aNumber := 22/7 . "aNumber is now an instance of Class Fraction"
aNumber := 3.14159 . "aNumber is now an instance of Class Float"
aNumber := 'Pi' . "aNumber is now an instance of Class ByteString"
There will be no warnings or exceptions for any of these statements.
Now that this doesn't work,
how do i add items to the list?
It depends on the type of list you are using.
Array is a fixed size with an index. OrderedCollection is an integer list of size variables. A set is a collection of unique objects. A dictionary is a collection of association objects, that is, the SortedCollection key-value pairs are a list of objects sorted by the definition of the collation.
Each of them has unique methods for adding elements.
The most common methods for standard collections are add:
(not available for Array or String - since they cannot change their cardinality after initial creation)
at:put:
(not available for Set, as it only contains keys, but no values)
We also have OrderedCollection addFirst:
, add:after:
, add:before:
,add:beforeIndex:
If you post an incremental message to the collection, but the collection doesn't understand that particular message, it throws an exception.
So, for your list
| list newElement1 newElement2 newElement3 |
list := OrderedCollection new .
newElement1 := 'ABC' . "a ByteString"
newElement2 := 123 . "a SmallInt"
newElement3 := Dictionary new .
newElement3 at: 'Doh' put: 'A deer, a female deer' ;
at: 'Ray' put: 'A drop of golden sun' ;
at: 'So' put: 'A needle pulling thread' .
list add: newElement1 ;
add: newElement2 ;
add: newElement3 .
will lead to
list (an OrderedCollection) [3 items] ('ABC' 123 aDictionary [2 items] ( 'Doh'->'A deer, a female deer' 'Ray'->'A drop of golden sun'))
source to share