Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

List vs ArrayList in java

In this post, we will see the difference between List and Arraylist in Java.
List is an interface where ArrayList is concrete implementation, so List is more generic than ArrayList.

You can instance an ArrayList in below two ways.You might have seen this code before.

// 1st way
List list=new ArrayList();
//2nd way
ArrayList arrayList=new ArrayList();

If you use 1st way, you can change the implementation later easily.
For example:
You need to change your implementation from ArrayList to LinkedList, you can simply change implementation, you don’t need to worry about making changes to all the code where variable list is being used.

List list=new LinkedList();

You won’t be able to do it in case of 2nd way.

It is always a good idea to code to an interface rather than concrete implementation.

List vs ArrayList

Let’s see tabular difference between List and ArrayList in java.

ImplementationList is interface and does not have any implementationArrayList is concrete implementation and ArrayList implements List interface
MethodsList method can access methods which is available in interface.
For example:
It can not access method trimToSize because it available in ArrayList
ArrayList contains extra methods such trimToSize(), ensureCapacity() which is not in List interface.
Changing ImplementationYou can change implementation later.
For example:
You want to change implementation from ArrayList to LinkedList, you can do it.
You can not change implementation as ArrayList is already concrete implementation.
RecommendationList is preferred over ArrayList as you can change implementationArrayList over List not preferred as you have to stick with ArrayList.You won't be able to change implementation later.

that’s all about List vs ArrayList in java.

The post List vs ArrayList in java appeared first on Java2Blog.

This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

List vs ArrayList in java


Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription