Difference Between List and ArrayList in Java

Difference Between List and ArrayList in Java

We would examine all the differences between List and ArrayList in Java.

First, I would like to say that both List and ArrayList are useful classes in Java. They both allow you to work with collection of item (whether primitive types or objects).

 

  1. About Lists
  2. About ArrayList
  3. Difference Between List and ArrayList

 

1. About List

First note that  List is an interface. So this means, you cannot instantiate it.

The List interface is available in Java.util.collection. It is derived from the Collection interface. A List is an ordered collection of objects which allows storage of duplicate values.

The List interface is implemented by the following classes:

  • ArrayList
  • LinkedList
  • Vector
  • Stack

How to create a list

If List is an interface and we cannot instantiate an interface, how then can we create a List? We do this using the constructor from any of the classes the implements the List interface. For example, see the code below

	List list1 = new ArrayList();
	List<Integer> list2 = new Stack();	
	List list3 = new LinkedList();

 

From the code, you can see that lists are created by calling the constructor of the derived classes.

 

 

2. About ArrayList

As mentioned before, an ArrayList implements the List interface.

ArrayList is similar to List. But unlike List, an ArrayList has specific method that are only available in the ArrayList class.

So to create an ArrayList, you use the ArrayList Constructor. See below

	ArrayList alist1 = new ArrayList();
	ArrayList<String> alist2 = new ArrayList<String>();

 

Similar to the List class, if an ArrayList is being created, you can decide to specify the datatype. If not specified, the default of object is used.

3. Differences Between List and ArrayList

  • An ArrayList is always a List but a List is not always an ArrayList
  • An ArrayList derives from the List interface
  • You create List using a constructor of one of its subclasses
  • You cannot Instantiate a List (of course, you cannot instantiate an interface). However, you can instantiate an ArrayList

 

Share this with friends