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

前端 未结 3 806
自闭症患者
自闭症患者 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 07:50

    The Values class implements a Collection that is backed by the HashMap. As mastov commented, Values is an inner class of HashMap, which gives it access to the members of the enclosing HashMap instance it is associated with. Therefore it's not empty. Its size is the size of the HashMap, and when you iterate over it, you are iterating over the Entries of the HashMap.

    When you call System.out.println(values);, you are calling the toString method of AbstractCollection, which uses an Iterator to iterate over the values and get their String representation. The Iterator actually iterates over the Entries of the HashMap and returns their values.

    The same goes for the Sets returned by keySet and entrySet.

提交回复
热议问题