除了大小之外。
例如:
并且。
例如:
|arr|. arr := Array new: 10
并且。
#(element1,element2, ...)
|arr|. arr := Array new: 10
#(element1,element2, ...)
Array with:
时,每次执行代码都会获得一个新的实例;而在使用 #( )
时,会在方法被接受/编译时创建实例,所以每次执行代码时,数组实例都是相同的。doSomething
array := #(6 7 8).
Transcript show: array.
array at: 1 put: 3.
第一次执行doSomething时,一切都会正常。第二次,您将看到打印了3、7、8,因为数组与上次调用该方法修改过的相同。
因此,在使用文字时应当小心,主要留给不会被改变的情况。
Example >> #threshold
^threshold
Example >> #threshold: anInteger
threshold := anInteger
Example >> #initialize
threshold := 0
Example class >> #new
^super new initialize
Example >> testArraySum
| a |
a := #(4 8 10).
a sum > threshold ifTrue: [ a at: 1 put: a first - 2 ].
^a sum
Example new testArraySum
多次运行后,你会得到20、18、16等结果...因为数组 #(4 8 10)被修改了。 另一方面,
Example >> testConstantArraySum
| a |
a := Array new: 3.
a at: 1 put: 4; at: 2 put: 8; at: 3 put: 10.
a sum > threshold ifTrue: [ a at: 1 put: a first - 2 ].
^a sum