开发者

Difference between usage of Interfaces and implementation classes in Java [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Type List vs type ArrayList in Java

Why is it recommended to do this:

List<String>开发者_开发知识库; myArrayList = new ArrayList<String>

or same with Map interface and HashMap class

rather than:

ArrayList<String> myArrayList = new ArrayList<String>


Because the consuming code of the myArrayList variable won't be tied to a particular implementation of this interface.


With the first (preferred) line you say, that your code needs a List, with the second line you say your code needs an ArrayList. Usually, you path variable instances around. If you now change the myArrayList instance for some reason you would have to change too much code.


You should not use:

List<String> myArrayList = new ArrayList<String>

Why you should use the type List instead of ArrayList (unless you really need feature of the ArrayList that is missing in the List interface) is already explained in the other answer.

But I think it is even more important to use proper names. So if you use List as type for the variable, the name should not tell that it is an ArrayList. It would be even better if the name indicated the use of the variable.

Yes, this is picky. But using good names will make it a lot easier to understand the code in a year from now and for colleagues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜