ArrayList Program in Java
In this tutorial, we have listed the top 12 ArrayList programs in Java for the best practices that will help you improve your coding skills.
All the ArrayList programs with explanation are based on the various operations, such as adding, removing, accessing, updating elements, etc.
If you are preparing for a Java technical test and interview, then having a good understanding of ArrayList and its usage can give you a good advantage.
These example programs based on ArrayList are very important for beginners and freshers and will help you crack interviews.
Recommend that before going to practice all these programs, you must read the tutorial ArrayList in Java that is very helpful to understanding the concepts of ArrayList.
How to add elements to ArrayList in Java Dynamically?
Let’s take an example program where we will add elements in the array list dynamically. Look at the source code.
Example 1:
package arrayListProgram;
import java.util.ArrayList;
import java.util.List;
public class ArrayListEx1 {
public static void main(String[] args)
{
// Creates an ArrayList object with an initial capacity of 10.
List<String> list = new ArrayList<String>();
// Call add() method to add elements at the end of the list using the reference variable list.
System.out.println("Adding elements to end of list");
list.add("A"); // Adding element at index 0.
list.add("B"); // Adding element at index 1.
list.add("D"); // Adding element at index 2.
list.add("E"); // Adding element at index 3.
list.add("G"); // Adding element at index 4.
System.out.println("ArrayList insertion order: " +list);
System.out.println("Adding an element at a specific index after B element.");
list.add(2, "C");
System.out.println("ArrayList insertion order after adding C: " +list );
System.out.println("Adding an element at a specific index after E");
list.add(5, "F");
System.out.println("ArrayList insertion order after adding F: " +list);
}
}
Output: Adding elements to the end of the list ArrayList insertion order: [A, B, D, E, G] Adding an element at a specific index after B element. ArrayList insertion order after adding C: [A, B, C, D, E, G] Adding an element at a specific index after E ArrayList insertion order after adding F: [A, B, C, D, E, F, G]
Explanation with diagram:
In this example program, when we added a new element ‘C’ at a specific index 2, elements D, E, and G are shifted to the one position left as shown in the above figure.
[adinserter block=”5″]
After inserting element C, the reference variable ‘list’ will reassign to the new array list and copy all the elements into the new ArrayList. The old default array list will be gone to the garbage collection.
Now the position of element E is shifted from position 3 to position 4 in the new ArrayList. Therefore, the element F after E has been added at position 5, not at position 4.
Let’s take an example program in which we will add elements of an array list into another array list using addAll() method.
Example 2:
package arrayListProgram;
import java.util.ArrayList;
public class ArrayListEx2 {
public static void main(String[] args)
{
// Creates an ArrayList1 with an initial capacity of 10.
ArrayList<String> al = new ArrayList<String>();
al.add("G");
al.add("H");
al.add("I");
al.add("M");
al.add("N");
System.out.println("Original ArrayList insertion order: " +al);
// Create another ArrayList2 with an initial capacity of 10.
ArrayList<String> al2 = new ArrayList<String>();
al2.add("J");
al2.add("K");
al2.add("L");
// Call addAll() method to add all elements of list2 at specific index 3.
al.addAll(3, al2);
System.out.println("ArrayList insertion order after adding group of elements in the list1 : " +al);
// Create ArrayList3 with initial capacity 10.
ArrayList<String> al3 = new ArrayList<String>();
al3.add("20");
al3.add("40");
al3.add("12");
// Adding group of elements at the end of array list1.
al.addAll(al3);
System.out.println(al);
}
}
Output: Original ArrayList insertion order: [G, H, I, M, N] ArrayList insertion order after adding a group of elements in the list1 : [G, H, I, J, K, L, M, N] [G, H, I, J, K, L, M, N, 20, 40, 12]
Java ArrayList Program based on Remove, Get, Contains, and Set methods
Let’s take an example program in which we will perform the following operations such as remove, get, contains, and set on elements of the list. Look at the source code.
Example 3:
package arrayListProgram;
import java.util.ArrayList;
public class ArrayListEx3 {
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("Science");
al.add("Maths");
al.add("Hindi");
al.add("English");
al.add("Social Science");
System.out.println("Original ArrayList insertion order: " +al);
// Call get() method to get element at the index 2.
// Since the return type of get method is String. So, we will store it using a variable str of type string.
String str = al.get(2);
System.out.println("Element at index 2: " +str);
// Call contains() method to check whether the element English is present in the list or not.
// Since the return type of contains method is boolean.
// So, we will store it by using a variable b of type boolean.
boolean b = al.contains("English");
// The contains() method returns true if the specified element is present in the list otherwise false.
System.out.println(b); // return true.
boolean b2 = al.contains("Sanskrit");
System.out.println(b2); // return false.
// This statement will return true if the collection contains all elements in the specified collection.
boolean bo = al.containsAll(al);
System.out.println(bo);
// call remove() method to remove element English at a specified index.
al.remove(3);
System.out.println("After removing element, ArrayList Order: " +al);
// Call set() method to replace element Social Science.
al.set(3, "Computer");
System.out.println("After replacing element, ArrayList Order: " +al);
}
}
Output: Original ArrayList insertion order: [Science, Maths, Hindi, English, Social Science] Element at index 2: Hindi true false true After removing element, ArrayList Order: [Science, Maths, Hindi, Social Science] After replacing element, ArrayList Order: [Science, Maths, Hindi, Computer]
Iteratating ArrayList using Iterator, ListIterator, Enumeration
Let’s take an example program in which we will iterate elements of array list using Iterator, ListIterator, Enumeration, and for loop.
Example 4:
package arrayListProgram;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ArrayListEx4 {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add(20);
list.add(25);
list.add(30);
list.add(35);
list.add(40);
System.out.println("Original ArrayList: " +list);
System.out.println("--Using Iterator--");
// Call iterator() method to iterate over the elements.
Iterator<Integer> itr = list.iterator();
// Checking the next element availability using reference variable itr.
while(itr.hasNext())
{
// Moving the cursor to next element using reference variable itr.
Integer it = itr.next(); // Here, return type is an integer.
System.out.println(it);
}
System.out.println("--Iterating in forwarding direction using ListIterator--");
// Call ListIterator() method to iterate over the elements.
ListIterator<Integer> litr = list.listIterator();
// Checking the next element availability using reference variable litr.
while(litr.hasNext())
{
Integer lit = litr.next();
System.out.println(lit);
}
System.out.println("--Using Enumeration-- ");
Enumeration<Integer> enumlist = Collections.enumeration(list);
while(enumlist.hasMoreElements())
{
System.out.println(enumlist.nextElement());
}
System.out.println("--Using Enhanced for loop--");
for(Integer in : list)
{
System.out.println(in);
}
}
}
}
Output: Original ArrayList: [20, 25, 30, 35, 40] --Using Iterator-- 20 25 30 35 40 --Iterating in forwarding direction using ListIterator-- 20 25 30 35 40 --Using Enumeration-- 20 25 30 35 40 --Using Enhanced for loop-- 20 25 30 35 40
ArrayList Program based on isEmpty, Size, and Clear methods
Let’s take an example program in which we will perform the following operations such as checking of elements in the list, size of list, and delete all elements from the list.
To perform these operations n the program, we will call three methods isEmpty(), size(), and clear() methods.
Example 5:
package arrayListProgram;
import java.util.ArrayList;
import java.util.List;
public class ArrayListEx5 {
public static void main(String[] args)
{
// Creates an array with an initial capacity of 10.
List<String> list = new ArrayList<String>();
// Call isEmpty() method to check elements in the list.
boolean b = list.isEmpty(); // It will return true if this list contains no elements.
System.out.println(b);
// Adding elements to the end of list.
list.add("INDIA");
list.add("USA");
list.add("SRILANKA");
list.add("JAPAN");
list.add("FRANCE");
System.out.println("Original ArrayList insertion order: " +list);
// Call size() method to get the number of elements or length of ArrayList in the list.
Integer sizelist = list.size();
System.out.println("Size/Length of the list: " +sizelist);
System.out.println(list.isEmpty()); // Return false.
System.out.println("--Clear all elements from the list--");
list.clear();
boolean bol = list.isEmpty();
System.out.println(bol);
Integer size = list.size();
System.out.println("No of elements in the list: " +size);
}
}
Output: true Original ArrayList insertion order: [INDIA, USA, SRILANKA, JAPAN, FRANCE] Size/Length of the list: 5 false --Clear all elements from the list-- true No of elements in the list: 0
ArrayList Program based on getting Index of First Occurrence of Element
Let’s write a Java program in which we will get the first occurrence of element from the list.
Example 6:
package arrayListProgram;
import java.util.ArrayList;
public class ArrayListEx6 {
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("ABC");
al.add("DEF");
al.add("ABC");
al.add("GHI");
al.add(null); // null element is allowed in the ArrayList.
System.out.println("Original ArrayList order:" +al);
// Call indexOf() method to get the index of the first occurrence of a specific element in the list.
Integer indexofElement = al.indexOf("ABC"); // It will return the index of the first occurrence of the element.
System.out.println("Index of the element ABC: " +indexofElement);
Integer indexElement = al.indexOf(null);
System.out.println("Index of the element null: " +indexElement);
Integer indexE = al.indexOf("JKL"); // It will return -1 if the element is not present in the list.
System.out.println("Index of the element JKL: " +indexE);
}
}
Output: Original ArrayList order:[ABC, DEF, ABC, GHI, null] Index of the element ABC: 0 Index of the element null: 4 Index of the element JKL: -1
ArrayList Program based on getting Index of Last occurrence of Element
Example 7:
package arraylistProgram;
import java.util.ArrayList;
public class ArrayListEx7 {
public static void main(String[] args)
{
ArrayList<Integer> arlist = new ArrayList<Integer>();
arlist.add(20);
arlist.add(25);
arlist.add(30);
arlist.add(35);
arlist.add(40);
arlist.add(25);
arlist.add(20);
System.out.println("Original ArrayList Order: " +arlist);
Integer lastindex = arlist.lastIndexOf(25);
System.out.println("Index of last occurrence of the element 25: " +lastindex);
Integer lindex = arlist.lastIndexOf(20);
System.out.println("Index of the element 20: " +lindex );
}
}
Output: Original ArrayList Order: [20, 25, 30, 35, 40, 25, 20] Index of last occurrence of the element 25: 5 Index of the element 20: 6
8. Assume that list1 is an array list that contains strings Apple, Mango, and Grapes, and list2 is another array list that contains strings Apple, Mango, and Guava.
Answer the following questions:
a. What are list1 and list2 after executing list1.addAll(list2)?
b. What are list1 and list2 after executing list1.add(list2)?
c. What are list1 and list2 after executing list1.removeAll(list2)?
d. What are list1 and list2 after executing list1.remove(list2)?
e. What are list1 and list2 after executing list1.retainAll(list2)?
f. What is list1 after executing list1.clear()?
Answer:
a) List1: [Apple, Mango, Grapes, Apple, Mango, Guava]
List2: [Apple, Mango, Guava]
b) Compile time error: The method add(String) in the type List<String> is not applicable for the arguments (List<String>).
c) List1: [Grapes]
List2: [Apple, Mango, Guava]
d) List1: [Apple, Mango, Grapes]
List2: [Apple, Mango, Guava]
e) List1: [Apple, Mango]
List2: [Apple, Mango, Guava]
f) List1: [ ]
9. What is wrong with each of the following code?
a. ArrayList<int> al = new ArrayList<int>();
b. ArrayList<String> al = new ArrayList();
c. ArrayList<String> al = new ArrayList<String>;
d. ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++)
{
al.set(i - 1, i * i);
}
e. ArrayList<Integer> al;
for (int i = 1; i <= 10; i++)
{
al.add(i * i);
}
Answer:
a) Syntax error.
b) No problem.
c) Syntax error.
d) IndexOutOfBoundsException
e) Compile time error: The local variable al may not have been initialized.
10. What is the output of the following program?
public class AddDemo
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("A");
al.add(0, "B");
al.add("C");
al.remove(1);
System.out.println(al);
}
}
Output: [B, C]
How to Sort Elements in ArrayList?
Let’s write a Java program in which we will sort elements in the ArrayList using Collections.sort() method. Here’s an example:
Example 8:
package arraylistProgram;
import java.util.ArrayList;
import java.util.Collections;
public class SortingArrayList {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(30);
list.add(10);
list.add(20);
list.add(40);
Collections.sort(list);
System.out.println(list);
}
}
Output: [10, 20, 30, 40]
How to convert ArrayList to Array in Java?
Let’s write a Java program in which we will convert ArrayList to an array using toArray() method. Here’s an example:
Example 9:
package arraylistProgram;
import java.util.ArrayList;
public class IteratingUsingStreamAPI {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("John");
list.add("Bob");
list.add("Mark");
list.add("Deep");
// Converting ArrayList into array.
String[] array = list.toArray(new String[list.size()]);
// Iterating array.
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
}
Output: John Bob Mark Deep
In this tutorial, we have listed the top 12 ArrayList program in Java with output and explanation. Hope that you will have liked the coding programs based on ArrayList and enjoyed it practicing. Stay tuned with our next tutorial where you will understand the realtime use of ArrayList in Java with the help of examples.
Thanks for reading!!!