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

前端 未结 4 1535
逝去的感伤
逝去的感伤 2020-12-06 17:36

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         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 17:44

    List names = new ArrayList();
    

    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 names = new //some other implementation of List
    

    Now if you do something as follows -

    ArrayList names = new ArrayList();
    

    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.

提交回复
热议问题