0

I am a little confused and looking for some clarification on the differences and different benefits for two different approaches for the declaration and instantiation of a Map.

What is the difference between

Map<String, String> myMap = new HashMap<String, String>;

AND

HashMap<String, String> myMap = new HashMap<String, String>;

What is the benefit or reason for declaring a superclass variable then instantiating it with a subclass?

Brian
  • 7,098
  • 15
  • 56
  • 73

2 Answers2

1

This is called "programming to the interface". (Map is an interface, not a class.) This allows code that only needs Map operations not to care which kind of Map it really is.

You could easily switch out the HashMap for, say, a TreeMap if you feel it's appropriate, and no other code would change.

Other similar questions:

Other references:

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

The first version uses a Hashmap for its implementation, but only exposes the members of Map in myMap.

In other words, you get the functionality of HashMap, but only through the interface of Map. It's done this way so that you can change out the implementation, but still use the same interface members.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501