How do HashMap.values() and HashMap.keySet() return values and keys?

前端 未结 3 804
自闭症患者
自闭症患者 2021-02-20 07:22

The source code of HashMap.values() is shown as follows

public Collection values() {
    Collection vs = values;
    return (vs !=         


        
3条回答
  •  迷失自我
    2021-02-20 08:03

    Collection vs = values;
    return (vs != null ? vs : (values = new Values()));
    

    These two line answer your question.

    values is a internal collection (Inherited from AbstractMap). If it is not null then it will be returned.
    If it is null then it will be initialized and the new one will returned.

    Now I guess, the main point of your question is
    when and how do these methods return objects with elements we need?

    Technically valuesalways return this initialized Object. Then how we get our entry values from these object.?
    Lets go a little deep:

    values() actually return an object of class Values which is an Inner class of HashMap and extends AbstractCollection

    private final class Values extends AbstractCollection 
    

    As you have looked into the source code. Then you will find inside the Values class

    public Iterator iterator() {
            return newValueIterator();
        }
    

    this newValueIterator() does the trick.
    If you go more deeper you will find newValueIterator() returns object of ValueIterator which is a subclass of HashIterator HashIterator implements basic functionality for iteration, which actually itterate over the table maintained by the HashMap.

提交回复
热议问题