Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some people use the List base class to instantiate a new ArrayList?

Tags:

java

I keep coming across code where people instantiate a new ArrayList and assign it to the List interface, like this:

List<String> names = new ArrayList<String>();

What is the reasoning behind this approach?

like image 847
S-K' Avatar asked Jul 03 '13 23:07

S-K'


2 Answers

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?

like image 147
nachokk Avatar answered Oct 16 '22 10:10

nachokk


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.

like image 43
JHS Avatar answered Oct 16 '22 10:10

JHS