简体   繁体   中英

What is the collection that HashMap.values() method in Java returns?

Java SE 6.0 API says values() method in java.util.HashMap returns a Collection type. How does JVM decide which collection to return at run time. Is it jvm specific or are there any general guidelines that Java follows. I browsed the source-code of HashMap but couldn't get a clue. Any help is highly appreciated, or if the question is lame, kindly point me why.Thanks.

You can see in the sources :

public Collection<V> values() {
    if (values == null) {
        values = new AbstractCollection<V>() {
          ...

They actually give a custom implementation of AbstractCollection .

An important thing to know about this collection is that it is NOT Serializable : never try to send it as-is between client-server.

Please note that this extract comes from the Sun JDK sources. It means that it is specific to the vendor implementation .

It's not JVM who decides which collection to return at runtime but the actual implementation of Map interface. In case of HashMap this is HashMap.Values inner class, see HashMap src

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM