[英]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.