0

New to Java, when I want to initialize a HashMap. I can find these two solutions:

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

I know Map is an interface, and HashMap implements it. But why we have two here? and what's the benefit for each of them?

Thilo
  • 257,207
  • 101
  • 511
  • 656
yuanheng zhao
  • 59
  • 1
  • 6
  • 1
    @MadPhysicist I did not change anything, just fixed the formatting. The generics were already there, but not visible in a regular text block. (Making them visible was the main purpose of my edit) – Thilo Jul 25 '19 at 02:33

1 Answers1

0

There is no difference between the objects; you have a HashMap in both cases. There is a difference in the interface you have to the object. In the first case, the interface is HashMap, whereas in the second it's Map. But the underlying object is the same.

The advantage to using Map is that you can change the underlying object to be a different kind of map without breaking your contract with any code that's using it. If you declare it as HashMap, you have to change your contract if you want to change the underlying implementation.

From : https://stackoverflow.com/users/157247/t-j-crowder In : What is the difference between the HashMap and Map objects in Java?