Skip to toolbar

Collection-2 || Use of ArrayList Class in Java.

ArrayList Class implements List Interface. In the last chapter, we have read about all the classes and their features as well as limitations. Now, we will understand all these concepts at the code level.

  • Class: ArrayList
  • Interface: List
  • Package: java.util

Key points of ArrayList

  • Stores objects as a list of elements and Any number of elements can be added to the list.
  • It is a resizable array which increases the array size whenever we add new items in the list.
  • Due to the above limitation Array is faster than ArrayList.
  • The default size of the ArrayList object is 10.
  • Ability to store similar as well as different types of elements to a single list.
  • It allows duplicate values in the list.
  • All the elements in the list remain in the same order in which we have added them even we add, remove, insert a new element in the list.
  • Each element has an integer type index value to locate in the list. like 0, 1, 2, 3 and so on.
  • Searching any specific value(element) in the list is slow.
  • Searching for any specific value(element) using the index number is fast on the list.
  • Traversing the list is faster.
  • Sorting the list is possible.
  • Use ArrayList, if you want to add/remove data from the end of the list.

Declaration of ArrayList

Using the below methods we could create a list for any type of non-primitive data type.

// Declaration of ArrayList
		ArrayList<String> stringList = new ArrayList<String>();
		ArrayList<Integer> integerList=new ArrayList<Integer>();
		List<String> list1=new ArrayList<String>();
		
		ArrayList stringList2=new ArrayList<String>();
		ArrayList integerList2=new ArrayList<Integer>();
		List list2=new ArrayList<String>();
		
		ArrayList list3=new ArrayList<>();
		List list4=new ArrayList<>();

Adding values into the ArrayList objects

As an example, we are taking one object for String and one for Integer type values. add() method is used to add values to the lists. We can add duplicate values in ArrayList. Items would be added to the list at the end of the list using add() method.

// Adding String values into the 'stringList' object.
		ArrayList<String> stringList=new ArrayList<String>();
		stringList.add("Java");
		stringList.add("C#");
		stringList.add("Selenium");
		stringList.add("Appium");
		stringList.add("TestNG");
		stringList.add("Java");
		
		// Adding Integer values into the 'integerList' object.
		ArrayList<Integer> integerList=new ArrayList<Integer>();
		integerList.add(10);
		integerList.add(20);
		integerList.add(30);
		integerList.add(10);

Adding different type of values in a single List object

Look at the declaration part, we haven’t mentioned any data type. Hence, we could add any type of data on the same List. But it is considered as a bad practice while programming.

// Adding mixed type of values into the single list
		ArrayList list3=new ArrayList<>();
		list3.add("Java");
		list3.add(10);
		list3.add(2.5);
		list3.add('a');
		list3.add(true);

Data manipulation within a list object

In this section will learn about basic operations and methods of ArrayList Objects.

  • Traversing of List using a for-each loop
  • Traversing of List using Iterator
  • Adding null value is allowed but it will throw an exception while traversing using the Iterator.
  • Getting the total number of items using size()
  • Getting index value based on the item value using indexOf(Object)
  • Accessing any item using the index key and get(index)
  • Add new data at the end of the list using add()
  • Adding data using index key in add(index, value)
  • removing specific data using the index or value in remove()
  • removing items using a reference of other list using removeAll(Collection)
  • Searching value or list using contains() and containsAll()

Traversing of List using a for-each loop

To traverse a list for-each loop is the best and easy method.

// Adding String values into the 'stringList' object.
		ArrayList<String> stringList=new ArrayList<String>();
		stringList.add("Java");
		stringList.add("C#");
		stringList.add("Selenium");
		stringList.add("Appium");
		stringList.add("TestNG");
		stringList.add("Java");
		
		// Traversing using for-each loop
		for (String string : stringList) 
		{
			System.out.println(string);
		}

Traversing of List using Iterator

Iterator is an Interface that is also used to convert list into the iterator object. It makes traversing easier.

Note: Adding null value is allowed but it will throw an exception while traversing using the Iterator.

  • 2 important methods in the Iterator object
    • hasNext(): Checks if iterator object has more items.
    • next(): returns next item from the list
// Adding mixed type of values into the single list
		ArrayList list3=new ArrayList<>();
		list3.add("Java");
		list3.add(10);
		list3.add(2.5);
		list3.add('a');
		list3.add(true);
		
	System.out.println("Traversing Mixed list using Iterator object.");
		Iterator iterator= list3.iterator();
		while(iterator.hasNext())
		{
			System.out.println(iterator.next());
		}

Getting the total number of items using size()

// Adding mixed type of values into the single list
		ArrayList list3=new ArrayList<>();
		list3.add("Java");
		list3.add(10);
		list3.add(2.5);
		list3.add('a');
		list3.add(true);
		
		System.out.println("Total Items: "+list3.size());

Output:
Total Items: 5

Getting index value based on the item value using indexOf(Object)

ArrayList<String> stringList1=new ArrayList<String>();
				stringList1.add("Java");
				stringList1.add("C#");
				stringList1.add("Selenium");
				stringList1.add("Appium");
				stringList1.add("TestNG");
				stringList1.add("Java");
				
                              System.out.printf("\nIndex value is %d for keyword.\n",stringList1.indexOf("TestNG"));

Output:
Index value is 4 for keyword.

Accessing any item using the index key and get(index)

As we all know, the index starts with 0, hence to access the 3rd element in the list we have to pass 2 as index value in the get(index) method.

// Adding mixed type of values into the single list
		ArrayList list3=new ArrayList<>();
		list3.add("Java"); // index=0
		list3.add(10);     // index=1
		list3.add(2.5);    // index=2
		list3.add('a');    // index=3
		list3.add(true);   // index=4
		
		System.out.println("Items at 3 poisition: "+list3.get(2));

Output:
Items at 3 poisition: 2.5

Add new data at the end of the list using add()

When we are using add() method to insert a new value into the list, it will automatically be added to the end of the list.

To understand this let’s develop a program to print the table of any value. In this example, we are using add() method only once but within a for a loop.

ArrayList<Integer> table=new ArrayList<Integer>();
		int keyValue=3;
		for(int i=1;i<=10;i++)
		{
			table.add(keyValue*i);
		}
		
		System.out.printf("Table of %d :\n",keyValue);
		for (Integer value : table) 
                {
			System.out.println(value);
                }

Output:
Table of 3 :
3
6
9
12
15
18
21
24
27
30

Adding data using index key in add(index, value)

It doesn’t replace the existing value in the list. It just inserts a new value into the list and pushes the remaining list one step forward.

ArrayList<Integer> table=new ArrayList<Integer>();
		int keyValue=3;
		for(int i=1;i<=10;i++)
		{
			table.add(keyValue*i);
		}
		
		System.out.printf("Table of %d :\n",keyValue);
		for (Integer value : table) {
			System.out.println(value);
		}
		
		table.add(3, 678);
		
		System.out.println("After adding value at 4th Position :");
		for (Integer value : table) {
			System.out.println(value);
		}

Output;
After adding value at 4th Position :
3
6
9
678
12
15
18
21
24
27
30

Removing specific data using the index or value in remove()

  • remove(index): removes the element from the specified index position
  • remove(value): search the first occurrence of the value in the list and removes the same. In the below example, only the first occurrence of value “Java” removed from the list.
// Adding String values into the 'stringList' object.
		ArrayList<String> stringList=new ArrayList<String>();
		stringList.add("Java");
		stringList.add("C#");
		stringList.add("Selenium");
		stringList.add("Appium");
		stringList.add("TestNG");
		stringList.add("Java");
		
		System.out.println("List before removing data:\n"+stringList);
		stringList.remove(2);
		System.out.println("\nList after removing data via item index:\n"+stringList);
		
		stringList.remove("Java");
		System.out.println("\nList after removing data via item value:\n"+stringList);


Ouput:
List before removing data:
[Java, C#, Selenium, Appium, TestNG, Java]

List after removing data via item index:
[Java, C#, Appium, TestNG, Java]

List after removing data via item value:
[C#, Appium, TestNG, Java]

Removing items using a reference of other list using removeAll(Collection)

In this example, we are using two different ArrayLists stringList and refList. Now, when we use the removeAll() method. It removes all the matching values from stringList using the values from refList.

Also, note that it removes all duplicate entries from the stringList. earlier we have two entries present for text “Java”.

// Adding String values into the 'stringList' object.
		ArrayList<String> stringList=new ArrayList<String>();
		stringList.add("Java");
		stringList.add("C#");
		stringList.add("Selenium");
		stringList.add("Appium");
		stringList.add("TestNG");
		stringList.add("Java");

// Adding mixed type of values into the single list
		ArrayList refList=new ArrayList<>();
		list3.add("Java");
		list3.add(10);
		list3.add(2.5);
		list3.add('a');
		list3.add("Appium");

// Removing values from 'stringList' using keys from 'list3'
		stringList.removeAll(refList);
		System.out.println("List after removing data using refernce of refList: "+stringList);

Output:
List before removing data:
[Java, C#, Selenium, Appium, TestNG, Java]

List after removing data using refernce of refList: 
[C#, Selenium, TestNG]

Searching value or list using contains() and containsAll()

// Adding String values into the 'stringList' object.
		ArrayList<String> stringList1=new ArrayList<String>();
				stringList1.add("Java");
				stringList1.add("C#");
				stringList1.add("Selenium");
				stringList1.add("Appium");
				stringList1.add("TestNG");
				stringList1.add("Java");
				
				if(stringList1.contains("Appium"))
				{
				    System.out.println("Keyword found.");
				}
				else
				{
				     System.out.println("Keyword not found.");
				}
				
				
				ArrayList stringList2=new ArrayList<>();
				stringList2.add("C#");
				stringList2.add("Java");
				stringList2.add("TestNG");
				stringList2.add("C#");
				
				if(stringList1.containsAll(stringList2))
				{
					System.out.println("Entire list found.");
				}
				else
				{
					System.out.println("Few items missing.");
				}
		

TestNG:

Computer Basics:

Java Basics:

Java Collection:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:

Selenium Tutorials:

JIRA:

Agile:


869total visits,2visits today

Leave a Reply

Your email address will not be published. Required fields are marked *

Site Statistics

  • Users online: 0 
  • Visitors today : 20
  • Page views today : 20
  • Total visitors : 48,216
  • Total page view: 66,362

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.