If you look at the keySet
declaration in the abstract class AbstractMap<K,V>
, you will see that it is defined as:
transient volatile Set<K> keySet;
Since it is volatile, reading it just once by using the local variable assignment is cheaper than reading it twice as would be in the other example you provided.
Furthermore, if you were to return the keySet
variable directly, then all the client code would be dealing with a volatile reference vs. a non-volatile reference (i.e. the Set<K> ks
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…