0

I know that List and Map are interfaces that can be implemented and ArrayList and HashMap are classes whose objects can be created and used.

I know the difference between the two pairs. My actual question is, is there a difference between the following two statements?

HashMap< K, V>  myMap = new HashMap<K, V>(); 
Map< K, V> myMap = new HashMap<K, V>();

And if there is, then what is the difference and when should I use which one? Similarly, what is the difference between:

ArrayList< Integer> myList = new ArrayList<Integer>();
List< Integer> myList = new ArrayList<Integer>();
halfer
  • 19,824
  • 17
  • 99
  • 186
LazyGuy
  • 715
  • 4
  • 12
  • 27

2 Answers2

2
HashMap< K, V> myMap = new HashMap(); 

is creating a instance of HashMap, as you see anywhere in Java.

Whereas:

Map< K, V> myMap = new HashMap();

is creating a instance of Map with a concrete implementation, called as Programming with interfaces.

The second way, i.e Programming with interfaces, brings the modularity to your program.

A nice explanation here, about what is the benefits and when to go for it:

What is the benefit of polymorphism using Collection interface to create ArrayList object?

halfer
  • 19,824
  • 17
  • 99
  • 186
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

ArrayList is a concrete implementation of List interface.

So the difference is in one you have concrete class reference in other you have interface reference.

HashMap< K, V>  myMap = new HashMap<K, V>(); //reference of concrete class HashMap
Map< K, V>  myMap = new HashMap<K, V>(); //reference of interface Map

You should always try to program with interfaces

NOTE: Program with interfaces should be used when you are passing the Map somewhere else, for local variables you are free to use concrete implementation.

Other difference is that on the Map one, you won't be able to call methods of HashMap

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120