6

I am reading the JDK source code. I see a method public Collection<V> values() in class HashMap:

   public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

But I think this logic will be shorter and more concise:

public Collection<V> values() {
    if (values == null) {
        values = new Values();
    }
    return values;
}

I think there must be a reason behind this. Please tell me why.

Boann
  • 48,794
  • 16
  • 117
  • 146
Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107
  • 1
    I think in earlier java versions the first snippet *would* be faster, as you'd need to load the variable only once into a local reference. Though in later versions that effect is negligible and you should just access the instance member directly – Lino May 19 '19 at 11:33
  • 1
    Similar question https://stackoverflow.com/questions/37957376/assign-instance-field-to-local-variable – Ori Marko May 19 '19 at 11:54
  • @Lino for concurrent code things _are very different_ when assigning to a local variable first; for non-concurrent it leads to smaller byte-code if that ever matters – Eugene May 19 '19 at 18:04

0 Answers0