The source code of HashMap.values()
is shown as follows
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}
As you can see, when the values()
method first called, it just returns a Values
object. The Values
object is a subclass of AbstractCollection
with no constructor, and of course contains no element. But when I called the method, it returned a collection rapidly
Collection<String> values = map.values();
System.out.println(values);
That's so weird. Not only values()
, but also keySet()
and entrySet()
method return such empty objects. So, here is my question, when and how do these methods return objects with elements we need?