11

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.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • 8
    Is there some reason you need to know what type of collection it is? – James Montagne Jun 18 '13 at 14:39
  • 2
    You could always try `System.out.println((new HashMap().values().getClass()));` – Peter Berg Jun 18 '13 at 14:40
  • 6
    Interesting, but you don't need to know. Many APIs expose their functionality via Interfaces, and the interfaces are all you need to know about. The internal implementations are not of consequence, and you should never write your code to assume a specific implementation. – NickJ Jun 18 '13 at 14:41
  • What am I missing here? I thought that `HashMap#values()` would return `Collection`. And if no types (K,V) are specified, it defaults to Object. – jnovacho Jun 18 '13 at 14:49
  • @NickJ Agreed. There is no logical reason why one would need to know the specific type of the collection returned by the `values()` function. If you do need a specific kind of collection (eg. for performance reasons), create and populate it from the collection returned from `values()` or write your own Map implementation. – RudolphEst Jun 18 '13 at 14:55
  • +1 RudolphEst particularly useful when you want to return the result of values() from server to client as this collection is not guaranteed to be Serializable (and is not in Sun JDK implementation). – Arnaud Denoyelle Jun 18 '13 at 15:00

2 Answers2

11

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.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
3

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275