Ved
Ved

Reputation: 8757

Why the coding should be "to the interface" especially for primitive datatypes?

I have a doubt on the design methodology that why we implement the code to the interface. This is very much observed in primitive data types. Like I am not getting the difference between these two :

Map<Integer, String> mymap = new HashMap<Integer, String>(); 

And

HashMap<Integer, String> mymap = new HashMap<Integer, String>();

Is there any difference between these two? I mean each and every place where we are going to use mymap will remain same in both the cases.

I am sorry if the question seems to be of no use but I really not getting that how this is going to make any difference later on where mymap will be used. Please help?

Thanks..

Note - I have already seen this question on SO but it is not giving what I want.

Upvotes: 2

Views: 1662

Answers (6)

soulcheck
soulcheck

Reputation: 36767

The second option limits you to always use HashMap, even if some day TreeMap could be more useful.

In the first one you can change the particular implementation easier - you only have to change one line of code. It's especially visible if you return your map from methods - the method return type doesn't have to change.

Coding to an interface also helps mocking the object during tests, but I assume that's not the case here.

Upvotes: 7

DNA
DNA

Reputation: 42586

The former allows you to change to:

Map<Integer, String> mymap = new TreeMap<Integer, String>(); 

for example, without breaking all the rest of your code.

A much more minor advantage is that your IDE can show you the methods for the interface, rather than the (potentially much larger number of) methods for the implementation.

Upvotes: 0

pap
pap

Reputation: 27614

In the specific instance you propose, it may not make a difference, but it's good practice to get yourself used to always use the interface in your declarations because there are legitimate instances where you will need that flexibility.

Upvotes: 0

Matthias
Matthias

Reputation: 12259

If you are only using this inside your type (meaning: private) and instantiate it yourself, it doesn't make a real difference.

It starts getting interesting if the public interface of your type exposes a Map vs. a HashMap.

Upvotes: 0

khachik
khachik

Reputation: 28703

Using Map mymap allows you to change the implementation later. For example, if at some point you need mymap to be ordered, you just change the initialization to LinkedHashMap.

Upvotes: 0

user647772
user647772

Reputation:

Because mymap can be instantiated somewhere else with a different implementation of Map, you should not rely on it being an instance of HashMap in the code using it.

Upvotes: 1

Related Questions