List in Selenium

The List is an ordered collection and can contain duplicate elements. You can access any element from its index. The list is more like an array with dynamic length; List is one of the most used Collection types.

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 world, 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 the 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.

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

Similar to the 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 an index.

The list is an 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 the 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 topmost class.

You can add a list inside a list as well.

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

obj.add("karthiq")
add(int index, Object o):

This add method adds the given value and accepts two parameters; 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 the 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:

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

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

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

We have unique indexes, so it is easy to remove an item from an index, but removing an 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; the set method does not 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

obj.indexOf("karthiQ")

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 decrease when we remove an element from the list.

The size() method returns the counter so that 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 the element is present then contains() method results in true otherwise false

obj.contains("karthiQ");

clear():

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.

obj.clear();

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(true);
		al.add(10);
		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"));

		al.clear();
		System.out.println("Elements present in list after clearing the list :" +al );
	}
}

The 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 is data in ArrayList 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 happen on this array.

What is the initial size of ArrayList?

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

What is the initial length of the underlying object array then?

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

If we are using the constructor with an argument, then the size of the 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 an 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, the 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 the default constructor.

In this case, the size of the 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 the 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 the underlying array, if it can accommodate the ArrayList after adding the current element.

For the first element, the size of ArrayList will become 1, so it will ensure the underlying array to be able to accommodate 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);
	ensureExplicitCapacity(paramInt);
}


if condition above will work only if the ArrayList is constructed from the 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 argument paramInt. Suppose of paramInt as the ‘wanted size’.

First insertion with the default constructor, paramInt=10.

private void ensureExplicitCapacity(int paramInt)
{
	this.modCount+=1;
	if(paramInt-this.elementData.length<<=0)
	{
		return;
	}
	grow(paramInt);
}


if condition above means that if the 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)
	j=paramInt;
	if(j-2147483639 >0)
		j=hugeCapacity(paramInt);
	this.elementdata  = Arrays.copyOf(this.elementData,j);
}


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

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

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

j= i+i/2 = 1.5i


The first insertion with default constructor j = 0. if(j-paramInt %lt0) says that if the target is still short of wanted size, then 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 the underlying array in ArrayList?

2147483639. Huge Capacity makes it up to 2147483647.

How does ArrayList create a new array while growing?

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

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

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

NO. The length remains the 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 ArrayList :

We can convert the Normal Arrays 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, ....so 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 the inner class in the ArrayList class.

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

Collections nCopies :

We can create and initialize the Arraylist of elements with the 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 the 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>();
     allElements.add("one");
     allElements.add("two");
     allElements.add("three");
     allElements.add("four");

     // Unsorted List
     System.out.println("***Before Sorting***");
     for(String element: allElements){
      System.out.println(element);
    }
     // Sort statement
     Collections.sort(allElements);

     // Sorted List
     System.out.println("***After Sorting***");
     for(String element: allElements){
      System.out.println(element);
    }
  }


the output of the sorting program

***Before Sorting***
one
two
three
four
***After Sorting***
four
one
three
two

Sort Arraylist In Descending Order

We do not have methods to reverse an ArrayList, but we have a 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>();
	 counts.add("One");
	   counts.add("Two");
	   counts.add("Three");
	   counts.add("Four");

	   /*Unsorted List: ArrayList content before sorting*/
	   System.out.println("===Before Sorting===");
	   for(String str: counts){
		System.out.println(str);
	  }
	   /* 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){
		System.out.println(str);
	  }
 }


the output of the descending program.

===Before Sorting===
One
Two
Three
Four
===ArrayList in descending order===
Two
Three
One
Four

Shuffle Arraylist

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

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

public static void main(String[] args) {
	ArrayList list = new ArrayList();
	list.add("Movie");
	list.add("Theatre");
	list.add("Watch");

	Collections.shuffle(list);
	System.out.println("Elements order after Shuffle :");
	for(String str: list){
		System.out.println(str);
	}
  }


The output of the shuffle program.

Elements order after Shuffle :
Watch
Theatre
Movie

Get Sublist of an ArrayList

Using the subList method, we can copy a few elements from the original ArrayList to sub ArrayList in Java.
It excludes the upper limit value; in the 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.add("Movie");
	list.add("Theatre");
	list.add("Watch");
	list.add("Avenger");

	List abc = list.subList(0, 2);

	System.out.println("Full ArrayList : "+list);
	System.out.println("Partial ArrayList : "+abc);
  }


The 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 both are not the same.

public static void main(String[] args) {
	ArrayList<String> listOne = new ArrayList<String>();
	listOne.add("Movie");
	listOne.add("Theatre");
	listOne.add("Watch");
	listOne.add("Avenger");

	ArrayList<String> listTwo = new ArrayList<String>();
	listTwo.add("Movie");
	listTwo.add("Theatre");
	listTwo.add("Watch");
	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 {
			flag=false;
			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");
   }
}


The 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

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions