简体   繁体   中英

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

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.

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?

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

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."?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM