java 警告避免使用像“HashMap”这样的实现类型;改用接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14396529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning Avoid using implementation types like 'HashMap'; use the interface instead
提问by Oomph Fortuity
I am getting this warning on Sonar:
我在声纳上收到此警告:
Avoid using implementation types like 'HashMap'; use the interface instead
避免使用像“HashMap”这样的实现类型;改用接口
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.
拜托,我想要适当的解决方案以避免对声纳发出警告。
回答by cowls
You should always code to an interface. ie. in this case you should declare your field like this:
您应该始终对接口进行编码。IE。在这种情况下,您应该像这样声明您的字段:
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
.
这样任何使用map
变量的东西都会把它当作类型Map
而不是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
这使您可以在以后更换地图的底层实现,而无需更改任何代码。你不再被束缚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?
另外我不确定你在做什么投射到Set
那里?
回答by PermGenError
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
回答by RoflcoptrException
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.
最大的优点是您以后可以随时更改 Map 的具体实现,而不会破坏代码。
To get more details about it, check out this question: What do programmers mean when they say, "Code against an interface, not an object."?
要获得有关它的更多详细信息,请查看以下问题:当程序员说“针对接口而不是对象进行编码”时,他们是什么意思?