[英]What's the difference between the Array and Literal Array in Smalltalk?
除了大小。
例如:
|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
真的是不变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.