简体   繁体   English

Smalltalk中Array和Literal Array之间有什么区别?

[英]What's the difference between the Array and Literal Array in Smalltalk?

Besides the size. 除了大小。

For example: 例如:

|arr|. arr := Array new: 10

and

#(element1,element2, ...)

In both forms the object created is going to be of the same type and with the same elements. 在这两种形式中,创建的对象将具有相同的类型并具有相同的元素。 The main difference is that while using Array with: you get a new instance each time the code is executed, with the #( ) you get the instance created when the method is accepted/compiled, so that each time the code is executed the instance of the array is the same. 主要区别在于使用Array with:每次执行代码时都会获得一个新实例,使用#( )可以获得在接受/编译方法时创建的实例,这样每次执行代码时都会执行实例数组是一样的。

Consider the following code: 请考虑以下代码:

doSomething
    array := #(6 7 8).
    Transcript show: array.
    array at: 1 put: 3.

the first time you execute doSomething everything will be normal. 第一次执行doSomething时一切都会正常。 The second time you will get 3, 7, 8 printed, because the array is the same that was modified the previous time the method was invoked. 第二次打印3,7,8,因为数组与上次调用方法时修改的数组相同。

So, you should be careful when using literals, and mainly leave them for cases where they are not going to be mutated. 因此,在使用文字时应该小心,主要是将它们留给不会发生变异的情况。

Consider this method in an example class with an instance variable threshold: 在具有实例变量阈值的示例类中考虑此方法:

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

Now, if you read the code of testArraySum, if threshold doesn´t change, it should always retunr the same, shouldn´t it? 现在,如果您读取testArraySum的代码,如果阈值没有改变,它应该总是重新调整,不是吗? Becasue you start setting a fixed value to a, then subtract (or not, depending on threshold, but we said it was fixed) a fixed amount, so it should be... 20. 你开始设置一个固定值为a,然后减去(或不,取决于阈值,但我们说它是固定的)一个固定的数量,所以它应该是...... 20。

Well, if you evaluate 好吧,如果你评价

Example new testArraySum

several times, you will get 20,18, 16... because the array #(4 8 10) gets modified. 好几次,你会得到20,18,16 ...因为数组#(4 8 10)被修改了。 On the other hand, 另一方面,

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

is really constant. 真的是不变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM