没有键或大小为 1 的值的弱身份键字典?

A WeakIdentityKeyDictionary with no keys or values of size 1?

在 Pharo 中试试这个脚本:

dictionary := WeakIdentityKeyDictionary new.
key := Object new.
dictionary at: key put: 'hello'.
dictionary size. " --> 1 "
key := nil.
2 timesRepeat: [Smalltalk garbageCollect].

现在字典应该是空的。然而:

dictionary keys isEmpty. " --> true"
dictionary values isEmpty. " --> true "

符合预期,但是

dictionary isEmpty. " --> false ??"
dictionary size. " --> 1 !! "

这似乎是设计使然。如果你看了WeakKeyDictionaryclass(WeakIdentityKeyDictionary的superclass)的评论:

I am a dictionary holding only weakly on my keys. This is a bit dangerous since at any time my keys can go away. Clients are responsible to register my instances by WeakArray such that the appropriate actions can be taken upon loss of any keys. As key may disappear at any time, my reported size may be greater than the number of keys encountered in iterations.

(强调我的)

字典的内部数组仍然有关联 nil --> 'hello',这就是为什么字典的 size 是 1,但 WeakIdentityKeyDictionaryassociationsDo: 检查 [=17] =] 键并避免对它们求值(见最后一行):

associationsDo: aBlock 
    "Evaluate aBlock for each of the receiver's elements (key/value 
    associations)."

    super associationsDo: [:association | | key | 
        "Hold onto the key so it won't be collected while the block is evaluated."
        key := association key.
        key ifNotNil:[aBlock value: association]].

Dictionary#associations 基于 associationsDo:,所以这就是为什么 dictionary associations 也是空的。