除了大小。
例如:
|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
现在,如果您阅读 testArraySum 的代码,如果阈值没有改变,它应该总是返回相同的,不是吗?因为您开始将固定值设置为 a,然后减去(或不减去,取决于阈值,但我们说它是固定的)固定量,所以它应该是...... 20。
好吧,如果你评价
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
真的是恒定的。