An advantage of doing something like
Map map = new HashMap<>();
is that your code is not dependent on the implementation of HashMap
nor its API.
If you later decide to substitute the HashMap
for another implementation of the Map
interface such as EnumMap
then the only part of your code that changes is that line.
Map map = new EnumMap<>();
Had you instead done something like
HashMap map = new HashMap<>();
and then decided to change from HashMap
to EnumMap
, you'd have to:
1) Go all over your code and change every instance of HashMap
to EnumMap
.
2) Redesign your code entirely if you depended on functionality that is present in HashMap
and not EnumMap
. That is, if you depended on an API that Map
does not support then you cannot necessarily and easily change from one type to another without doing additional modifications to your code.