Why using list = new arraylist () better than arraylist list?

Source: Internet
Author: User

This is called programming to interface. This will be helpful in case if you wish to move to some other implementation of list in the future. If you want some methods inArrayListThen you wowould need to program to the implementation that isArrayList a = new ArrayList().

 

 

The main reason you 'd do this is to decouple your code from a specific implementation of the interface. When you write your code like this:

List list = new ArrayList();

The rest of your code only knows that data is of TypeList, Which is preferable because it allows you to switch between different implementations ofListInterface with parameters.

For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library withLinkedList. If your library relies heavily on accessing elements in these lists, then eventually you'll find that you 've made a poor design demo-; you'll realize that you shold have usedArrayList(Which gives O (1) Access time) instead ofLinkedList(Which gives O (n) Access time). Assuming you have been programming to an interface, making such a change is easy. You wowould simply change the instanceListFrom,

List list = new LinkedList();

To

List list = new ArrayList();

And you know that this will work because you have written your code to follow the contract provided byListInterface.

On the other hand, if you had implemented the core of your library usingLinkedList list = new LinkedList(), Making such a change wouldn't be as easy, as there is no guarantee that the rest of your code doesn't make use of methods specific toLinkedListClass.

All in all, the choice is simply a matter of design... but this kind of design is very important (especially when working on large projects), as it will allow you to make implementation-specific changes later without breaking existing code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.