Friday, January 19, 2018

How to use Java List Interface and ArrayList with example

What is a list?
Java List is a sub interface of Java Collection. It is an ordered collection of objects with methods to add, modify and delete objects. List allows duplicates. Objects/data can be accessed using index notation. 
Actual implementation of List interface is provided by ArrayList, LinkedList, Vector and Stack classes. We will see an example of List interface with ArrayList implementation. 

Difference between Array and List 
Array is fixed length data structure, One cannot change the length after creating the Array object whereas List is dynamic in size. As elements are added to an ArrayList its capacity grows automatically. Arrays store homogeneous type of data, whereas List can store heterogeneous data or objects.  

Use Case 
We will see an example of List’s ArrayList implementation in which we will create a customer object and add few customers to an ArrayList and print out object data by iterating over the list. We will use eclipse IDE for this demo. First create a Java Project and create a Customer class which is a POJO class as follows.