Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning Avoid using implementation types like 'HashMap'; use the interface instead

Tags:

java

I am getting this warning on Sonar:

Avoid using implementation types like 'HashMap'; use the interface instead

What does it mean?

The class in which i get this warning is as:

class A {
   private HashMap<String, String> map=new HashMap<String, String>();

   //getters and setters

}

Please, I want proper solution to avoid warning on Sonar.

like image 746
Oomph Fortuity Avatar asked Jan 18 '13 10:01

Oomph Fortuity


3 Answers

You should always code to an interface. ie. in this case you should declare your field like this:

private Map<String, String> map= new HashMap<String, String>();

This way anything using the map variable will treat it as type Map rather than HashMap.

This allows you to swap out the underlying implementation of your map at a later date without having to change any code. You are no longer tied to HashMap

Read through this question: What does it mean to "program to an interface"?

Also I am not sure what you were doing casting to a Set there?

like image 132
cowls Avatar answered Nov 15 '22 13:11

cowls


I dont use Sonar, but what the warning basically means is

Always program to an interface rather than implemnetation class

private Map<String, String> map= new HashMap<String, String>();
        Interface                    Implementing class
like image 5
PermGenError Avatar answered Nov 15 '22 14:11

PermGenError


Generally, you should always implement against an interface instead of a concrete type. In this example it means you should write your code like that:

private Map<String, String> map= new HashMap<String, String>();

The big advantage is that you can then later always change the concrete implementation of your Map without breaking the code.

To get more details about it, check out this question: What do programmers mean when they say, "Code against an interface, not an object."?

like image 4
RoflcoptrException Avatar answered Nov 15 '22 14:11

RoflcoptrException