I keep coming across code where people instantiate a new ArrayList and assign it to the List interface, like this:
List names = new ArrayList&l
List<String> names = new ArrayList<String>();
With that you write code against the interface List
, which makes it easy to switch the implementation in the future if you have to.
In that case the following will suffice -
List<String> names = new //some other implementation of List
Now if you do something as follows -
ArrayList<String> names = new ArrayList<String>();
You will code against the implementation ArrayList
itself. And your code is tied to that specific implementation. In case if you have to switch the implementation then it will require a lot of code changes.
Check the docs to discover some of the standard implemenation provided by Java 6.
To decouple your code from a specific implementation of the interface.
This also helps you to move to another implementation of the List
interface in the future.
For example -
You have List<String> names = new ArrayList<String>();
later on you decide that you should have used some other implementation of the List
interface, say LinkedList
so you would just change it to List<String> names = new LinkedList<String>();
and nothing breaks.
Programming to an interface, not an implementation
It's a design pattern from Gang of Four (GoF). Why is that?
You guide by abstract contract instead of concrete implementation.
public class MyClass {
private List myList ;
public setMyList(List list){
myList=list;
}
}
what about instead of ArrayList
implementation you want LinkedList
implementation?
in that way you only has to inject that property with the setter.
Abstraction is the key, you don't know nothing about implementation only guide by specification.
Read this What does it mean programming to an interface?
Such code doesn't use the List
class, it declares the variable as being of type List
. This is called abstraction
List
is an interface, which defines what methods the actual class has, without specifying which actual class is used.
Although not a big deal here, this practice can be very important, even essential in more complexes situations. It's good practice to always follow this pattern.