List in Java

List is an ordered collection and can contain duplicate elements. You can access any element from its index.

List is more like array with dynamic length, List is one of the most used Collection type.

In my language : List is nothing but a library, what do you think about 'How the books are stored in the Library'

In any Library in the work they will store it in the racks which have some ISBN or some unique number.

If you ask a Librarian to bring a book which is in '12371' rack, now librarian will go to that rack and fetches the book.

Probably if you ask he may not do, but he will fetch if someone from higher official asks.

Library can hold more number of same book , isn't it ?, because it is stored in a rack which has unique numbers.

Similar to library the list collection also stores the objects based on the index number, and it can also store duplicate objects as the access is going to happen through index.

List is a interface, and it just provides what should be present if somebody implements the interface, so the list interface will not have any implementations.

ArrayList and LinkedList classes provide implementation to the List interface methods, the methods present in the ArrayList and LinkedList are same with little changes

Methods present in List :

There are few frequently used methods in java list, I would be discussing them:

add( Object o):

This method adds an element/value into the list based on the index. Here the index is calculated automatically based on the number of existing elements

As said earlier, the Collection accepts only Object class type, so if you store any other type, those will be upcasted to Object class because Object class is top most class.

You can add a list inside a list as well.

In below code, String value will be stored as Object type only and the value will be stored at the last position in the list.

add(int index, Object o):

This add method adds the given value and accepts two parameter; one the index where you want to add the value, two Object O is the value to be added.

When you add a value at a given position; then the element which existing at that position will be moved to next position, so every element in the list.

You will face IndexOutOfBoundsException exception if you try to add value to the index which does not exist in the list.

obj.add(2, boolean)			

Remove method is overloaded method, There are two remove() methods in List.

First remove method accepts a index of int type and removes a object at the given position., Second remove() method accepts value of object type and removes the value by searching the total list one by one till it finds the matching element.

remove() method which works based on index is much faster than the remove method which works on the element values.

We have unique indexes so it is easy to remove a item from a index but removing a element by value involves in comparing all the object from the beginning of the List.

After removing an element, the element after that index will move one step closer to the beginning of the list.

obj.remove(int index) // faster	
obj.remove(Object o)  // slower
set(int index, Object o):

set method updates the element value at a given index, set method doesnot return any value.

obj.set(4, "karthiQ")
// sets element at index 4 to "karthiQ"
int indexOf(Object o):

indexOf method retrieves the index of the first matching object o. If the element is not found in the list then this method returns the value -1.

indexOf method returns int values


Object get(int index):

get fetches the value at a given position, returns Object value.

obj.get(2); // retrieves the value at position 2

int size():

size() method works based on the number of elements in the list.

There is a counter (variable) inside the list, which will increase by one when we add an element to the list and decreases when we remove a element from the list.

The size() method returns the counter , so we would have the number of elements present in the list as output.

size() method returns int value.

obj.size(); // total number of elements in the list

boolean contains(Object o):

contains() method checks whether the given element is present in the list or not. If element is present then contains() method results in true otherwise false



clear() method is used for removing all the elements of the list in one go, this will not delete the list but elements in the list.

Complete program for the list operations.

package cherchertech;

import java.util.ArrayList;
import java.util.List;

public class OverLoading {
	public static void main(String[] args) {
		List al  = new ArrayList();
		al.add("chercher tech");
		al.add(new ArrayList());
		System.out.println("value at index 2 before Adding value at 2 : " +al.get(2));
		al.add(2, 20);
		System.out.println("value at index 2 after Adding value at 2 : " +al.get(2));
		al.remove("chercher tech");  // based on object
		System.out.println("All values in list : " +al);
		al.remove(1); // based on index
		System.out.println("All values in list : " +al);
		al.set(1, "eee");
		System.out.println("Value at index 1 :" +al.get(1));
		System.out.println("index of avengers (none present): "+ al.indexOf("Avenger"));
		System.out.println("get the value at index 0 " +al.get(0));
		System.out.println("Number of elements present in the list : "+al.size());
		System.out.println("does list contains 'eee' : "+al.contains("eee"));
		System.out.println("Elements present in list after clearing the list :" +al );

Output of the above program is :

value at index 2 before Adding value at 2 : 10
value at index 2 after Adding value at 2 : 20
All values in list : [true, 20, 10, []]
All values in list : [true, 10, []]
Value at index 1 :eee
index of avengers (none present): -1
get the value at index 0 true
Number of elements present in the list : 3
does list contains 'eee' : true
Elements present in list after clearing the list :[]

How ArrayList internally Works

how data in arraylist is getting stored internally?

Arraylist class stores the data in an one-dimentional array of java.lang.Object type.

Below is the piece of declaration from the ArrayList class:

									private transient Object[] elementData;

All the addition, removal and traversal happens on this array.

what is the initial size of arraylist?

Initial size of ArrayList is 0. Size of ArrayList is the number of elements it has. It is different from length of the underlying Array.

what is the initial length of underlying object array then?

If we are using default constructor to create and ArrayList, then size of underlying array is 0.

If we are using constructor with argument, then the size of underlying array will be the integer number we are passing as the argument to the constructor.

can the initial length of arraylist be increased?

YES. As stated above, ArrayList provides a constructor with argument where we can provide the initial length of the underlying array.

									public ArrayList (int paramInt)

what is the initial / default capacity of arraylist?

Well, initial or default capacity of ArrayList is 10. Again, see the code excerpt from the ArrayList class which confirms the same:

									private static final int DEFAULT_CAPACITY = 10;

Initial / default capacity comes into consideration when we create the list from default constructor.

In this case, size of array becomes 10 for the first insertion into the ArrayList. Well, we will discuss the complete logic when we will discuss grow().

The length of underlying array becomes 10.

how add() method of arraylist works internally?

Here is the code excerpt of ArrayList’s add method:

									public boolean add(E paramE)
										ensureCapacityInternal(this.size + 1);
										this.elementData[(this.size++)] = paramE
										return true;

First, it ensures the capacity of underlying array, if it can accomocate the ArrayList after adding the current element.

For first element, size of arraylist will become 1, so it will ensure the underlying array to be able to accomodate 1 element.

Now, let’s see how it ensures that:

									private void ensureCapacityInternal(int paramInt)
										if(this.elementData == EMPTY_ELEMENTDATA)
										paramInt = Math.max(10,paramInt);

if condition above will work only if the ArrayList is constructed from default constructor and we are adding the first element.

In other words, if ArrayList is constructed from argumented constructor OR we have already added an element, above if condition will skips.

Why? Because, at the time of default constructor, EMPTY_ELEMENTDATA is assigned to elementData array.

									private static final Object[] EMPTY_ELEMENTDATA = new Object[0];
									public ArrayList(){
										this.elementData = EMPTY_ELEMENTDATA

Now, the call goes to ensureExplicitCapacity with argement paramInt. Suppose of paramInt as the ‘wanted size’.

First insertion with default constructor, paramInt=10.

									private void ensureExplicitCapacity(int paramInt)


if condition above means that if size of the underlying array is greater than ‘wanted size’, the return (do nothing).
If not, then GROW.

First insertion with default constructor if (10 -0) <=0 => false. GROW.

Here is the grow(), in case it goes for grow:

									private void grow(int paramInt){
										int i = this.elementData.length;
										int j = i+ (i>>1);
										if(j-paramInt <0)
										if(j-2147483639 >0)
										this.elementdata  = Arrays.copyOf(this.elementData,j);

i is size of underlying array. First insertion with default constructor i=0;

j is the target size of underlying array. j is 1.5 times i. How?

When left shift of 1 will make a number half. i>>1 will make i/2.

									j= i+i/2 = 1.5i

First insertion with default constructor j = 0. if(j-paramInt %lt0) says that if target is still short of wanted size then make make the target size = wanted size.

First insertion with default constructor j= 10

Then it checks for MAX Size to which an array could possibly grow.

hugeCapacity(), increases the size by 8 of MAX_SIZE.

what is the max _size of underlying array in arraylist?

2147483639. Huge Capacity makes it upto 2147483647.

how does arraylist creates new array while growing?

ArrayList uses Arrays.copyOf() to copy the current data to new Array. This function return the array with new size.

Internally, Arrays.copyOf() calls System.arraycopy() which is a native function.

while removing the element from arraylist, does the length of underlying array decreases?

NO. Length remains same. Target data gets removed and data gets shifted. That’s all.

Initialize Arraylist

We can initialize an Arraylist in multiple ways, we will learn widely used methods in here:

Convert the Array into an Arraylit :

We can convert the Normal Arryas into Arraylists, this method will be useful when we want to grow the Array of elements.

								ArrayList obj = new ArrayList(Arrays.asList(Object obj1, Object obj2, Object obj3, on));			

Full code for converting Array into ArrayList:

								public static void main(String args[]) {
									ArrayList obj = new ArrayList<String>(Arrays.asList("google", "chercher tech", "bing"));
									System.out.println("Elements Present in ArrayList are :"+obj);

Arraylist using Inner class :

We can form an Arraylist using inner class in Arraylist class.

								public static void main(String[] args) {
									ArrayList languages = new ArrayList(){{
									  System.out.println("Arraylist Elements are:"+languages);

Collections nCopies :

We can create and initialize the Arraylist of elements with same values using Collections.ncopies method, in this way all the Arraylist elements will have only one value.

In below example an Arraylist with 3 elements will be crated with values of '1'

								public static void main(String[] args) {
									ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(3, 1));
									System.out.println("ArrayList items using nCopies: "+list);

Sort Arraylist :

We can sort the elements in any collection using Collections class method called sort(), we can sort the strings and the Integers.

public static void main(String args[]){
     ArrayList<String> allElements = new ArrayList<String>();
     // Unsorted List
     System.out.println("***Before Sorting***");
     for(String element: allElements){
     // Sort statement
     // Sorted List
     System.out.println("***After Sorting***");
     for(String element: allElements){

output of the sorting program

***Before Sorting***
***After Sorting***

Sort Arraylist In Descending Order :

We donot have methods to reverse a ArrayList, but we have method to reverse an Arraylist.

Are you able to figure out now, how we can reverse the Arraylist.

Yes, Your guess is right: Sort the Arraylist(sorts in ascending order), now reverse the Sorted Arraylist, you will descending Arraylist. TADA.

 public static void main(String[] args) {
	ArrayList<String> counts = new ArrayList<String>();
	   /*Unsorted List: ArrayList content before sorting*/
	   System.out.println("===Before Sorting===");
	   for(String str: counts){
	   /* Sorting in decreasing order*/
	   Collections.sort(counts, Collections.reverseOrder());
	   /* Sorted List in reverse order*/
	   System.out.println("===ArrayList in descending order===");
	   for(String str: counts){

output of descending program.

===Before Sorting===
===ArrayList in descending order===

Shuffle Arraylist

List stores the element based on the insertion order, but you can shufffle the List.

Call the shuffle() static method from the Collections class in Java.Util.

public static void main(String[] args) {
	ArrayList list = new ArrayList();
	System.out.println("Elements order after Shuffle :");
	for(String str: list){

Output of the shuffle program.

Elements order after Shuffle :

Get Sublist of an ArrayList

Using subList method we can copy few elements from original ArrayList to sub Arraylist in Java.
It excludes the upper limit value, in below example it will copy elements from 0 to 1 but it will exclude upper limit 2.

public static void main(String[] args) {
	ArrayList list = new ArrayList();
	List abc = list.subList(0, 2);
	System.out.println("Full ArrayList : "+list);
	System.out.println("Partial ArrayList : "+abc);

Output of the sub ArrayList program.

Full ArrayList : [Movie, Theatre, Watch, Avenger]
Partial ArrayList : [Movie, Theatre]		

Compare Two ArrayLists in Java

We can compare Lists using for loop, but before going through the loop we have to check the number of elements in each of them, if the list size mismatches then we can say bot are not same.

public static void main(String[] args) {
	ArrayList<String> listOne = new ArrayList<String>();
	ArrayList<String> listTwo = new ArrayList<String>();
	listTwo.add("Avengers Infinity War");
	boolean flag = true;
   if(listOne.size() == listTwo.size()) {
	   for (int i = 0; i < listOne.size(); i++) {
		if(listOne.get(i).equals(listTwo.get(i))) {
			System.out.println("Elements are same");
		}else {
			System.out.println("Element at position "+i+ " "
					+ "are not same value 1 >"+ listOne.get(i) +" value 2> "+listTwo.get(i));
   else {
	   System.out.println("Whatt, both are not");
   if(flag) {
	   System.out.println("*******************Lists are same");
   }else {
	   System.out.println("*******************Lists are not same");

Output of the List comparison

Elements are same
Elements are same
Elements are same
Element at position 3 are not same value 1 >Avenger value 2> Avengers Infinity War
*******************Lists are not same			

Join My Facebook Group
Join Group

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Selenium-Webdriver.Com [Group]
Facebook Group · 801 members
Join Group
Learn Selenium Webdriver Concepts and Interview Questions Learn and code
Copyright © CherCher Tech