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

5

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.

share  improve this question   
  • 1
    Why are you casting the map to a set? – kennytm Jan 18 '13 at 10:07

3 Answers

17
 

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?

share  improve this answer   
  •  
    I'd agree it's a generally good practice, but I take issue with the "always" in your first sentence. It's perfectly likely that you might end up needing specialized methods of a LinkedList or LinkedHashSet or LinkedHashMap, for instance, in which case you won't be able to resort to the interface. At least not in Java where there's no compostive datatype declaration syntax and you aren't able to say something like "I want something that's the intersection of the Map and List interfaces". If you end up passing around the interface, then you lose context. – haylem Jul 8 '14 at 7:41
  •  
    Beware also that always using the base interface might hide behavioral implementation details. For instance, if you use an immutable List, maybe resorting to the List interface instead of directly an ImmutableList (or another type) is not the best idea, as you convey the wrong impression that your object satisfies the List interface, which it doesn't. So, there definitely are exceptions to this rule. – haylem Jul 8 '14 at 7:42
  •  
    Thats true regarding the use of specialized methods, though these cases are very rare so I wouldnt worry too much abouyt the wording :). I think with regard to your second point I would still use the interface as it leaves you with the option to reuse code if you decide to use other list implementations later. You just need to use correct exception handling. – cowls Jul 8 '14 at 7:50 
posted @   八英里  阅读(737)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示