Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance of collection in JAVA [duplicate]

Tags:

java

Possible Duplicate:
Why should the interface for a Java class be prefered?
What is the benefit of polymorphism using Collection interface to create ArrayList object?

I see in many examples that when one creates an instance of some collection like TreMap, he uses it's base as type:

Map<String,String> theMap = new TreeMap<String,String>();

Why not to use

TreeMap<String,String> theMap = new TreeMap<String,String>(); 
like image 567
kenny Avatar asked Dec 27 '22 11:12

kenny


2 Answers

Because it's considered a better practice to code to the interface (Map) instead of the implementation (TreeMap). This way you are free to switch to a different implementation (e.g. HashMap, if you later decide it is a better solution) with minimal code touch-points.

like image 141
maerics Avatar answered Jan 17 '23 13:01

maerics


It's generally better to code to an interface, not an implementation, which allows an implementation change without having to change code that refers to it.

The only time it's reasonable to not do this is when code relies on characteristics of a specific implementation. For example, if the code requires the fast indexed list item access ArrayList provides, it might make sense to force a specific implementation.

like image 25
Dave Newton Avatar answered Jan 17 '23 15:01

Dave Newton