Array: Difference between revisions

Line 221:
 
Array
<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).
 
"another array literal (i.e. constant); also immutable; notice the 5th element being another array"
a2 := #(1.0 20.0 'thirty' true #(5 5 5)).
"a new created array; all 10 elements are initially nil"
a4 := Array new:10. "all 10 elements are nil"
 
"an new created array with computed5 elements computed from expressions (at run time)"
a3 := { 10 . 20 . (a1 at:3) . 40 squared }.</lang>
 
accessing:
<lang smalltalk>"access by index (notice: in Smalltalk index starts at 1)"
a1 at:2. -> 20
a1 at:index put:100. -> error; immutable
Line 247 ⟶ 248:
 
"enumerating"
a1 do:[:e | e printCR ] -> prints each element
a1 select:[:e | e > 20]. -> #(30 40)
a1 collect:[e | e squared]. -> #(100 400 900 1600)
Line 259 ⟶ 260:
#(200 300 400) asByteArray -> error raised
(#(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"
Anonymous user