Array: Difference between revisions
Content added Content deleted
Line 221: | Line 221: | ||
Array |
Array |
||
<lang smalltalk>"an array literal (i.e. constant); this is immutable |
<lang smalltalk>"an array literal (i.e. constant); this is immutable. |
||
Array literals are constructed at compile time (thus the following costs effectively nothing)" |
|||
a1 := #(10 20 30 40). |
a1 := #(10 20 30 40). |
||
"another array literal |
"another array literal; notice the 5th element being another array" |
||
a2 := #(1.0 20.0 'thirty' true #(5 5 5)). |
a2 := #(1.0 20.0 'thirty' true #(5 5 5)). |
||
"a new created array; all 10 elements are nil" |
"a new created array; all 10 elements are initially nil" |
||
a4 := Array new:10. |
a4 := Array new:10. |
||
"an new created array with |
"an new created array with 5 elements computed from expressions (at run time)" |
||
a3 := { 10 . 20 . (a1 at:3) . 40 squared }.</lang> |
a3 := { 10 . 20 . (a1 at:3) . 40 squared }.</lang> |
||
accessing: |
accessing: |
||
<lang smalltalk>"access by index" |
<lang smalltalk>"access by index (notice: in Smalltalk index starts at 1)" |
||
a1 at:2. -> 20 |
a1 at:2. -> 20 |
||
a1 at:index put:100. -> error; immutable |
a1 at:index put:100. -> error; immutable |
||
Line 247: | Line 248: | ||
"enumerating" |
"enumerating" |
||
a1 do:[:e | e printCR ] |
a1 do:[:e | e printCR ] -> prints each element |
||
a1 select:[:e | e > 20]. -> #(30 40) |
a1 select:[:e | e > 20]. -> #(30 40) |
||
a1 collect:[e | e squared]. -> #(100 400 900 1600) |
a1 collect:[e | e squared]. -> #(100 400 900 1600) |
||
Line 259: | Line 260: | ||
#(200 300 400) asByteArray -> error raised |
#(200 300 400) asByteArray -> error raised |
||
(#(65 66 67) collect:#asCharacter) asString -> 'ABC' |
(#(65 66 67) collect:#asCharacter) asString -> 'ABC' |
||
#(1 2 3 1 2 3 4) asSet. -> Set(1 2 3 4) |
|||
#(1 2 3 1 2 4) asBag. -> Bag(1*2 2*2 3 4) |
|||
#(1 2 3 1 2 4) asSortedCollection. -> SortedCollection(1 1 2 2 3 4) |
|||
"searching" |
"searching" |