Java ArrayList Programs

The ArrayList in Java is a resizable array implementation of the List interface. It provides dynamic arrays that can grow as needed, offering a flexible way to handle sequences of elements.

This blog post will teach you 15+ ArrayList Java programs with output and step-by-step explanations.

1. Java Program to Add Elements to an ArrayList

In this program, we use the add(E e) method to add elements to the ArrayList and the add(int index, E element) method to add an element at a specific index.

Program Steps

1. Create an ArrayList.

2. Add elements to the ArrayList using the add(E e) method.

3. Use the add(int index, E element) method to add an element at a specific index.

4. Print the ArrayList to show the added elements.

Code Program

import java.util.ArrayList;

public class AddElementsToArrayList {
    public static void main(String[] args) {
        // Step 1: Creating an ArrayList of String type
        ArrayList<String> fruits = new ArrayList<>();

        // Step 2: Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Displaying the ArrayList after adding elements
        System.out.println("ArrayList after adding elements: " + fruits);

        // Step 3: Adding an element at a specific index
        fruits.add(1, "Blueberry");

        // Displaying the ArrayList after inserting an element at index 1
        System.out.println("ArrayList after inserting Blueberry at index 1: " + fruits);
    }
}

Output:

ArrayList after adding elements: [Apple, Banana, Cherry]
ArrayList after inserting Blueberry at index 1: [Apple, Blueberry, Banana, Cherry]

Explanation:

1. An ArrayList named fruits is created to store strings. This step demonstrates initializing an ArrayList which will hold elements of type String.

2. Three strings representing different fruits are added to the ArrayList using the add(E e) method. This method appends each new element to the end of the list, demonstrating how to populate an ArrayList with data.

3. The add(int index, E element) method is used to insert "Blueberry" into the ArrayList at index 1. This operation shifts the element that was at this position (Banana) and any subsequent elements to the right (increases their indices). This illustrates how to insert elements into specific positions within an ArrayList.

4. The program prints the contents of the ArrayList after each addition to show how the list changes with each operation, demonstrating the dynamic nature of ArrayList and its ability to adjust to new elements.

2. Java Program to Remove Elements from an ArrayList

Removing elements from an ArrayList can be performed in various ways, including by specifying the element directly with remove(Object o) or by its index with remove(int index). These methods make managing the contents of ArrayList both straightforward and efficient, allowing for the dynamic adjustment of the collection's size during runtime.

Program Steps

1. Create an ArrayList and populate it with elements.

2. Remove an element from the ArrayList by specifying its value.

3. Remove an element from the ArrayList by specifying its index.

4. Print the ArrayList after each removal to observe the changes.

Code Program

import java.util.ArrayList;

public class RemoveElementsFromArrayList {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList of Strings
        ArrayList<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Yellow");

        // Displaying the ArrayList before removals
        System.out.println("Original ArrayList: " + colors);

        // Step 2: Removing an element by its value
        colors.remove("Green");

        // Displaying the ArrayList after removing "Green"
        System.out.println("ArrayList after removing Green: " + colors);

        // Step 3: Removing an element by its index
        colors.remove(2); // Removing "Yellow" which is now at index 2

        // Displaying the ArrayList after removing the element at index 2
        System.out.println("ArrayList after removing element at index 2: " + colors);
    }
}

Output:

Original ArrayList: [Red, Green, Blue, Yellow]
ArrayList after removing Green: [Red, Blue, Yellow]
ArrayList after removing element at index 2: [Red, Blue]

Explanation:

1. An ArrayList named colors is created and populated with strings representing colors. This demonstrates how to initialize and populate an ArrayList.

2. The remove(Object o) method is used to remove the "Green" element from the ArrayList. This shows how to remove an element by specifying its value, which shifts any subsequent elements to the left (subtracts one from their indices).

3. The remove(int index) method is used to remove the element at index 2 from the ArrayList, which, after the previous removal, is "Yellow". This illustrates how to remove an element by its index, also shifting subsequent elements to the left.

4. After each removal operation, the contents of the ArrayList are printed. This demonstrates the effect of each remove operation on the ArrayList, highlighting how the size and contents of the list change dynamically as elements are removed.

3. Java Program to Update ArrayList Elements

The set(int index, E element) method is used to replace the element at the specified position in this list with the specified element. This method is particularly useful when you need to update the value of an existing element based on its position.

Program Steps

1. Create an ArrayList and populate it with initial elements.

2. Update an element in the ArrayList by specifying its index and the new value.

3. Print the ArrayList before and after the update to observe the changes.

Code Program

import java.util.ArrayList;

public class UpdateArrayListElements {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList
        ArrayList<String> cars = new ArrayList<>();
        cars.add("Volvo");
        cars.add("BMW");
        cars.add("Ford");
        cars.add("Mazda");

        // Displaying the ArrayList before updates
        System.out.println("Original ArrayList: " + cars);

        // Step 2: Updating an element at a specific index
        cars.set(1, "Tesla"); // Updating the second element (index 1)

        // Displaying the ArrayList after updates
        System.out.println("Updated ArrayList: " + cars);
    }
}

Output:

Original ArrayList: [Volvo, BMW, Ford, Mazda]
Updated ArrayList: [Volvo, Tesla, Ford, Mazda]

Explanation:

1. An ArrayList named cars is created and initially populated with a list of car brand names. This setup demonstrates the initialization and population of an ArrayList with string elements.

2. The set(int index, E element) method is used to update the element at index 1 (the second element in the list) from "BMW" to "Tesla". This shows how to modify an element in an ArrayList by specifying its index and the new value to assign to it.

3. The program prints the contents of the ArrayList before and after the update operation. This output demonstrates the change in the ArrayList's contents, highlighting the effectiveness of the set method for updating list elements.

4. Java Program to Increase the Current Capacity of an ArrayList

The ensureCapacity(int minCapacity) method of ArrayList ensures that the instance has at least the specified number of elements of space. This preemptive approach can be particularly useful when the approximate number of elements is known beforehand, avoiding incremental reallocation costs.

Program Steps

1. Create an ArrayList and populate it with a few elements.

2. Check the current capacity of the ArrayList.

3. Use the ensureCapacity() method to increase the capacity of the ArrayList.

4. Add more elements to demonstrate that additional space is available without reallocation.

Code Program

import java.util.ArrayList;

public class IncreaseArrayListCapacity {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");

        // Step 2: Increasing the capacity of the ArrayList
        // Unfortunately, Java does not provide a direct method to get the current capacity of an ArrayList.
        // We'll increase the capacity to a higher number.
        list.ensureCapacity(100);

        // Adding more elements to the ArrayList
        for (int i = 0; i < 95; i++) {
            list.add("New Element " + i);
        }

        // Displaying the size of the ArrayList to demonstrate that it has grown.
        System.out.println("Size of the ArrayList after additions: " + list.size());
    }
}

Output:

Size of the ArrayList after additions: 98

Explanation:

1. An ArrayList named list is created and initially populated with three programming language names. This step demonstrates the creation and population of an ArrayList.

2. The ensureCapacity(100) method is called to request that the ArrayList increases its capacity to at least 100 elements. While Java doesn't allow directly checking the capacity of an ArrayList, this step ensures that adding a large number of elements won't require frequent reallocation.

3. Additional elements are then added to the ArrayList using a loop. This demonstrates that after increasing the capacity, the ArrayList can accommodate a large number of additions without needing to resize.

4. The size of the ArrayList is printed out, which reflects the total number of elements it contains after the additions. This output confirms that the ArrayList has been successfully expanded and populated beyond its initial size, demonstrating the effect of using ensureCapacity() to optimize for scenarios where the expected number of elements is known in advance.

5. Java Program for Iterating Over an ArrayList (different ways)

Java provides several ways to iterate through ArrayList elements, including traditional for loops, enhanced for loops, iterator objects, and Java 8's forEach method, along with lambda expressions. Each method has its use cases and benefits, making it important to understand how to apply them effectively.

Program Steps

1. Create an ArrayList and populate it with some elements.

2. Iterate over the ArrayList using a traditional for loop.

3. Iterate over the ArrayList using an enhanced for loop.

4. Iterate over the ArrayList using an iterator.

5. Iterate over the ArrayList using the forEach method with a lambda expression.

Code Program

import java.util.ArrayList;
import java.util.Iterator;

public class IteratingArrayList {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList
        ArrayList<String> languages = new ArrayList<>();
        languages.add("Java");
        languages.add("Python");
        languages.add("C++");
        languages.add("JavaScript");

        // Step 2: Using a traditional for loop
        System.out.println("Using traditional for loop:");
        for (int i = 0; i < languages.size(); i++) {
            System.out.println(languages.get(i));
        }

        // Step 3: Using an enhanced for loop
        System.out.println("\nUsing enhanced for loop:");
        for (String language : languages) {
            System.out.println(language);
        }

        // Step 4: Using an iterator
        System.out.println("\nUsing iterator:");
        Iterator<String> iterator = languages.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Step 5: Using forEach with a lambda expression
        System.out.println("\nUsing forEach with lambda expression:");
        languages.forEach((language) -> System.out.println(language));
    }
}

Output:

Using traditional for loop:
Java
Python
C++
JavaScript
Using enhanced for loop:
Java
Python
C++
JavaScript
Using iterator:
Java
Python
C++
JavaScript
Using forEach with lambda expression:
Java
Python
C++
JavaScript

Explanation:

1. An ArrayList named languages is created and populated with names of programming languages. This step demonstrates initializing and populating an ArrayList.

2. A traditional for loop iterates over the ArrayList using an index to access each element. This method is useful when you need the index during iteration.

3. An enhanced for loop (also known as "for-each" loop) provides a simpler way to iterate over each element without using an index. It's best used when the index is not needed.

4. An iterator is used to iterate over the ArrayList. This method provides a way to safely remove elements during iteration, which is not possible with the for-each loop.

5. The forEach method with a lambda expression provides a concise and expressive way to iterate over each element, introduced in Java 8. This method is best for executing a single operation or method call on each element of the collection.

6. Java Program to Sort an ArrayList

Sorting an ArrayList in Java is a common task that can be accomplished in several ways, including using the Collections.sort() method for natural ordering or custom ordering. Additionally, Java 8 introduced the List.sort() method, which allows sorting with a Comparator. Sorting is a powerful utility that enables efficient data manipulation and retrieval, especially when working with large datasets. This program will demonstrate how to sort an ArrayList of strings and integers using different approaches.

Program Steps

1. Create an ArrayList of strings and populate it with some elements.

2. Sort the ArrayList of strings using Collections.sort().

3. Create an ArrayList of integers and populate it with some elements.

4. Sort the ArrayList of integers using the List.sort() method with a lambda expression as the comparator.

Code Program

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortArrayList {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList of Strings
        ArrayList<String> countries = new ArrayList<>();
        countries.add("India");
        countries.add("Australia");
        countries.add("South Africa");
        countries.add("Denmark");

        // Step 2: Sorting the ArrayList of Strings
        Collections.sort(countries);
        System.out.println("Sorted ArrayList of Strings: " + countries);

        // Step 3: Creating and populating an ArrayList of Integers
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(1);
        numbers.add(4);
        numbers.add(2);
        numbers.add(3);

        // Step 4: Sorting the ArrayList of Integers
        numbers.sort(Comparator.naturalOrder());
        System.out.println("Sorted ArrayList of Integers: " + numbers);
    }
}

Output:

Sorted ArrayList of Strings: [Australia, Denmark, India, South Africa]
Sorted ArrayList of Integers: [1, 2, 3, 4, 5]

Explanation:

1. An ArrayList of strings named countries is created and populated with names of countries. This demonstrates how to initialize and populate an ArrayList.

2. The Collections.sort() method is used to sort the ArrayList of strings in natural order (alphabetically). This method modifies the original list.

3. An ArrayList of integers named numbers is created and populated with some integers. This step shows another example of initializing and populating an ArrayList, but this time with integer elements.

4. The List.sort() method with Comparator.naturalOrder() is used to sort the ArrayList of integers in natural ascending order. The use of a lambda expression as the comparator parameter allows for concise code to define the sorting order.

7. Java Program for Searching Elements in an ArrayList

Searching for elements in an ArrayList is a common operation in Java programming. It can be performed using methods like contains(Object o), which checks if the list contains the specified element, and indexOf(Object o), which returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element. These methods provide a straightforward way to search for the presence of elements within ArrayList, making it easier to handle collections of data.

Program Steps

1. Create an ArrayList and populate it with elements.

2. Use the contains() method to check if the ArrayList contains a specific element.

3. Use the indexOf() method to find the index of a specific element in the ArrayList.

Code Program

import java.util.ArrayList;

public class SearchArrayList {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");
        list.add("JavaScript");

        // Step 2: Checking if an element exists using contains()
        boolean exists = list.contains("Python");
        System.out.println("Does the list contain Python? " + exists);

        // Step 3: Finding the index of an element using indexOf()
        int index = list.indexOf("C++");
        System.out.println("Index of C++ in the list: " + index);
    }
}

Output:

Does the list contain Python? true
Index of C++ in the list: 2

Explanation:

1. An ArrayList named list is created and populated with names of programming languages. This demonstrates how to initialize and populate an ArrayList.

2. The contains(Object o) method is used to check if "Python" is an element of list. It returns true because "Python" exists in the list, showing how to verify the presence of an element in an ArrayList.

3. The indexOf(Object o) method is employed to find the index of "C++" in list. It returns 2, indicating that "C++" is the third element in the list (as indexing starts from 0). This illustrates how to find the position of an element within an ArrayList.

8. Java Program to Convert Array to ArrayList and Vice Versa

In Java, arrays and ArrayLists are two common ways to store collections of elements. However, they serve different purposes and have different characteristics. Arrays are fixed in size and can hold primitive data types and objects, while ArrayLists are part of the Java Collections Framework, are resizable, and can only hold objects. Converting between arrays and ArrayList is a common operation. This process involves converting a fixed-size array to a dynamic ArrayList for more flexibility or converting an ArrayList to an array for performance or API compatibility reasons.

Program Steps

1. Convert an array to an ArrayList.

2. Convert an ArrayList to an array.

Code Program

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

public class ArrayAndArrayListConversion {
    public static void main(String[] args) {
        // Step 1: Convert an array to an ArrayList
        String[] array = {"Java", "Python", "C++"};
        List<String> arrayList = new ArrayList<>(Arrays.asList(array));
        System.out.println("Array to ArrayList: " + arrayList);

        // Step 2: Convert an ArrayList to an array
        ArrayList<String> listOfLanguages = new ArrayList<>();
        listOfLanguages.add("JavaScript");
        listOfLanguages.add("TypeScript");
        listOfLanguages.add("Kotlin");
        String[] languageArray = listOfLanguages.toArray(new String[0]);
        System.out.println("ArrayList to Array: " + Arrays.toString(languageArray));
    }
}

Output:

Array to ArrayList: [Java, Python, C++]
ArrayList to Array: [JavaScript, TypeScript, Kotlin]

Explanation:

1. To convert an array to an ArrayList, we first create a String array named array containing programming languages. Using Arrays.asList(array) converts the array to a list, which is then used to initialize an ArrayList named arrayList. This demonstrates converting a static array to a dynamic ArrayList that allows for more flexible operations.

2. To convert an ArrayList to an array, we start by creating an ArrayList of strings named listOfLanguages and adding elements to it. The toArray(new String[0]) method is called on listOfLanguages to convert it to an array named languageArray. The new String[0] argument specifies the type of the array to return. This demonstrates converting a dynamic ArrayList back into a static array, which may be necessary for compatibility with APIs that require arrays or for performance optimizations.

9. Java Program to Compare Two ArrayLists

Comparing two ArrayLists in Java is a common task when working with collections. It can involve checking if two lists are equal, which means they contain the same elements in the same order, or if one list contains all the elements of another list regardless of the order. Java provides multiple ways to perform these comparisons, such as using the equals() method for equality checks and the containsAll() method for containment checks. Understanding how to compare ArrayLists is essential for manipulating and analyzing collections effectively.

Program Steps

1. Create two ArrayLists and populate them with elements.

2. Compare the two ArrayLists for equality using the equals() method.

3. Compare the two ArrayLists for element containment using the containsAll() method.

Code Program

import java.util.ArrayList;

public class CompareArrayLists {
    public static void main(String[] args) {
        // Step 1: Creating and populating ArrayLists
        ArrayList<String> list1 = new ArrayList<>();
        list1.add("Java");
        list1.add("Python");
        list1.add("C++");

        ArrayList<String> list2 = new ArrayList<>();
        list2.add("Java");
        list2.add("Python");
        list2.add("C++");

        ArrayList<String> list3 = new ArrayList<>();
        list3.add("Python");
        list3.add("C++");
        list3.add("Java"); // Note: Same elements as list1 but different order

        // Step 2: Comparing list1 and list2 for equality
        boolean isEqual = list1.equals(list2); // Checks for equality including order
        System.out.println("list1 equals list2: " + isEqual);

        // Step 3: Comparing list1 and list3 for element containment
        boolean isContained = list1.containsAll(list3); // Checks if all elements of list3 are in list1
        System.out.println("list1 contains all elements of list3: " + isContained);
    }
}

Output:

list1 equals list2: true
list1 contains all elements of list3: true

Explanation:

1. Three ArrayLists named list1, list2, and list3 are created and populated with elements. list1 and list2 contain the same elements in the same order, while list3 contains the same elements as list1 but in a different order.

2. The equals() method is used to compare list1 and list2 for equality. It returns true because both lists contain the same elements in the exact same order, demonstrating how to check if two lists are equal.

3. The containsAll() method is used to check if list1 contains all elements of list3. It returns true, indicating that list1 does contain all the elements of list3, regardless of the order. This demonstrates how to check if one list contains all elements of another list, regardless of their order.

11. Java Program to Handle ArrayList of Objects

Working with ArrayList of objects in Java is a fundamental part of object-oriented programming. It allows developers to store objects in a resizable array, providing flexibility and powerful data manipulation capabilities. This functionality is particularly useful when dealing with collections of custom objects, such as a list of employees, products, or any other entities. This program will demonstrate how to create, populate, and manipulate an ArrayList of custom objects, including how to add, iterate over, and remove elements.

Program Steps

1. Define a custom class to represent the objects stored in the ArrayList.

2. Create an ArrayList to store objects of the custom class.

3. Populate the ArrayList with objects.

4. Iterate over the ArrayList and display the properties of each object.

5. Remove an object from the ArrayList.

Code Program

import java.util.ArrayList;

// Step 1: Defining a custom class
class Employee {
    String name;
    int age;

    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{name='" + name + "', age=" + age + '}';
    }
}

public class ArrayListOfObjects {
    public static void main(String[] args) {
        // Step 2: Creating an ArrayList to store Employee objects
        ArrayList<Employee> employees = new ArrayList<>();

        // Step 3: Populating the ArrayList with Employee objects
        employees.add(new Employee("John Doe", 30));
        employees.add(new Employee("Jane Doe", 25));
        employees.add(new Employee("Steve Smith", 28));

        // Step 4: Iterating over the ArrayList and displaying each Employee
        System.out.println("Employees list:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }

        // Step 5: Removing an Employee from the ArrayList
        employees.remove(1); // Removing Jane Doe
        System.out.println("\nEmployees list after removal:");
        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

Output:

Employees list:
Employee{name='John Doe', age=30}
Employee{name='Jane Doe', age=25}
Employee{name='Steve Smith', age=28}
Employees list after removal:
Employee{name='John Doe', age=30}
Employee{name='Steve Smith', age=28}

Explanation:

1. A custom class Employee is defined with properties name and age, along with a constructor to initialize these properties and an overridden toString() method for displaying employee details.

2. An ArrayList named employees is created to store objects of type Employee.

3. The ArrayList is populated with Employee objects, demonstrating how to add objects to the list.

4. The program iterates over the ArrayList using an enhanced for loop, displaying the properties of each Employee object. This shows how to access and manipulate elements in an ArrayList of objects.

5. An Employee object is removed from the ArrayList using the remove(int index) method. The program then iterates over the ArrayList again to display the updated list of employees, demonstrating how the list is modified after the removal.

12. Java Program to Filter Elements in an ArrayList

Filtering elements in an ArrayList is a common requirement in many Java applications. It involves selecting elements that satisfy certain criteria and discarding the rest. Java 8 introduced the Stream API, which provides a more declarative approach to processing sequences of elements, including filtering collections based on various conditions. This program will demonstrate how to use the Stream API to filter elements in an ArrayList, making the code more readable and expressive.

Program Steps

1. Create an ArrayList and populate it with some elements.

2. Use the Stream API to filter elements based on a condition.

3. Collect the filtered elements back into an ArrayList.

Code Program

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FilterArrayListElements {
    public static void main(String[] args) {
        // Step 1: Creating and populating an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);

        // Step 2: Using the Stream API to filter elements
        List<Integer> filteredNumbers = numbers.stream() // Converting the ArrayList to a Stream
                .filter(number -> number % 2 == 0) // Filtering even numbers
                .collect(Collectors.toList()); // Collecting the filtered elements back into a List

        // Step 3: Displaying the filtered ArrayList
        System.out.println("Filtered ArrayList (Even Numbers): " + filteredNumbers);
    }
}

Output:

Filtered ArrayList (Even Numbers): [2, 4, 6]

Explanation:

1. An ArrayList named numbers is created and populated with integers from 1 to 6. This step demonstrates how to initialize and populate an ArrayList.

2. The Stream API's filter() method is used to filter the ArrayList. The numbers.stream() method converts the ArrayList into a stream. The filter() method takes a predicate (a lambda expression) that specifies the filtering condition (in this case, selecting even numbers). The collect(Collectors.toList()) method collects the filtered elements back into a new List.

3. The filtered list, which contains only the even numbers from the original ArrayList, is then printed to the console. This demonstrates how to effectively filter elements in a collection using the Stream API and lambda expressions for concise and expressive code.

13. Java Program to Synchronize an ArrayList

ArrayList in Java is not synchronized, which means it is not thread-safe and can cause issues when accessed by multiple threads simultaneously. In a multithreaded environment, it's crucial to synchronize the ArrayList to avoid concurrent modification exceptions and ensure data consistency. Java provides a wrapper Collections.synchronizedList(List list) method that returns a synchronized (thread-safe) list backed by the specified list. This blog post demonstrates how to synchronize an ArrayList and access it safely from multiple threads.

Program Steps

1. Create an ArrayList.

2. Synchronize the ArrayList using Collections.synchronizedList().

3. Access the synchronized ArrayList from multiple threads.

Code Program

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

public class SynchronizeArrayList {
    public static void main(String[] args) {
        // Step 1: Creating an ArrayList
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");

        // Step 2: Synchronizing the ArrayList
        List<String> syncList = Collections.synchronizedList(list);

        // Step 3: Accessing the synchronized ArrayList from multiple threads
        Thread thread1 = new Thread(() -> {
            synchronized (syncList) {
                syncList.forEach(System.out::println);
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (syncList) {
                syncList.add("JavaScript");
                System.out.println("Added JavaScript");
            }
        });

        thread1.start();
        thread2.start();
    }
}

Output:

Java
Python
C++
Added JavaScript
(Or a variation of this output depending on the thread execution order)

Explanation:

1. An ArrayList named list is created and populated with several programming languages. This step demonstrates how to initialize and populate an ArrayList.

2. The ArrayList is synchronized using Collections.synchronizedList(list), which wraps the original list in a synchronized list stored in syncList. This synchronized list is thread-safe.

3. Two threads, thread1 and thread2, are created to access the synchronized list. thread1 iterates over syncList and prints each element, while thread2 adds a new element ("JavaScript") to syncList. Both threads synchronize on syncList to ensure thread safety during iteration and modification. This demonstrates how to safely access a synchronized list from multiple threads, preventing concurrent modification exceptions and ensuring data consistency.

14. Java Program to Implement Stack Using ArrayList

A stack is a fundamental data structure that follows the Last In, First Out (LIFO) principle. It allows operations such as push (to add an item to the top), pop (to remove the top item), and peek (to view the top item without removing it). While Java has a Stack class, implementing a stack using an ArrayList can provide more flexibility and performance benefits. This blog post demonstrates how to implement a stack data structure using an ArrayList in Java, including methods for push, pop, and peek operations.

Program Steps

1. Define a Stack class that uses an ArrayList for storage.

2. Implement the push method to add elements to the stack.

3. Implement the pop method to remove and return the top element of the stack.

4. Implement the peek method to return the top element without removing it.

5. Create a driver method to demonstrate the stack operations.

Code Program

import java.util.ArrayList;

class Stack<T> {
    private ArrayList<T> elements;

    public Stack() {
        elements = new ArrayList<>();
    }

    // Step 2: Push method
    public void push(T item) {
        elements.add(item);
    }

    // Step 3: Pop method
    public T pop() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot pop from an empty stack.");
        }
        return elements.remove(elements.size() - 1);
    }

    // Step 4: Peek method
    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot peek from an empty stack.");
        }
        return elements.get(elements.size() - 1);
    }

    public boolean isEmpty() {
        return elements.isEmpty();
    }
}

public class StackUsingArrayList {
    public static void main(String[] args) {
        // Step 5: Demonstrating stack operations
        Stack<String> stack = new Stack<>();

        stack.push("Java");
        stack.push("Python");
        stack.push("C++");

        System.out.println("Top element (peek): " + stack.peek());

        System.out.println("Pop element: " + stack.pop());
        System.out.println("Pop element: " + stack.pop());

        System.out.println("Top element (peek) after pops: " + stack.peek());
    }
}

Output:

Top element (peek): C++
Pop element: C++
Pop element: Python
Top element (peek) after pops: Java

Explanation:

1. A generic Stack class is defined, using an ArrayList to store elements. This design allows the stack to handle any type of objects.

2. The push method adds an element to the top of the stack by appending it to the end of the ArrayList.

3. The pop method removes and returns the top element of the stack. It first checks if the stack is empty to prevent errors. The method removes the last element of the ArrayList, which represents the top of the stack.

4. The peek method returns the top element without removing it, similarly checking for an empty stack before accessing the last element of the ArrayList.

5. The main method demonstrates stack operations by creating a Stack instance, pushing elements onto the stack, peeking at the top element, popping elements off the stack, and then peeking again to show the state of the stack after some operations. This demonstrates the LIFO behavior of the stack.

15. Java Program to Implement Queue Using ArrayList

A queue is a fundamental data structure that operates in a First In, First Out (FIFO) manner. It supports two primary operations: enqueue (adding an item to the end of the queue) and dequeue (removing the item at the front of the queue). Unlike stacks, queues ensure that the first element added is the first one to be removed. Implementing a queue using an ArrayList in Java allows for dynamic resizing and provides a simple way to manage collections of elements with FIFO access patterns.

Program Steps

1. Define a Queue class that uses an ArrayList for storage.

2. Implement the enqueue method to add elements to the end of the queue.

3. Implement the dequeue method to remove and return the front element of the queue.

4. Implement the peek method to view the front element without removing it.

5. Create a driver method to demonstrate queue operations.

Code Program

import java.util.ArrayList;

class Queue<T> {
    private ArrayList<T> elements;

    public Queue() {
        elements = new ArrayList<>();
    }

    // Step 2: Enqueue method
    public void enqueue(T item) {
        elements.add(item);
    }

    // Step 3: Dequeue method
    public T dequeue() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot dequeue from an empty queue.");
        }
        return elements.remove(0);
    }

    // Step 4: Peek method
    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty.");
        }
        return elements.get(0);
    }

    public boolean isEmpty() {
        return elements.isEmpty();
    }
}

public class QueueUsingArrayList {
    public static void main(String[] args) {
        // Step 5: Demonstrating queue operations
        Queue<String> queue = new Queue<>();

        queue.enqueue("Java");
        queue.enqueue("Python");
        queue.enqueue("C++");

        System.out.println("Front element (peek): " + queue.peek());

        System.out.println("Dequeue element: " + queue.dequeue());
        System.out.println("Dequeue element: " + queue.dequeue());

        System.out.println("Front element (peek) after dequeues: " + queue.peek());
    }
}

Output:

Front element (peek): Java
Dequeue element: Java
Dequeue element: Python
Front element (peek) after dequeues: C++

Explanation:

1. A generic Queue class is defined, using an ArrayList to store elements. This approach leverages the dynamic resizing capability of ArrayList while providing FIFO queue behavior.

2. The enqueue method adds an element to the end of the queue by appending it to the ArrayList. This simulates adding an item to the back of the queue.

3. The dequeue method removes and returns the front element of the queue. It first checks if the queue is empty to avoid errors. The method removes the first element of the ArrayList, which represents the front of the queue.

4. The peek method returns the front element without removing it, checking first to ensure the queue is not empty. This allows viewing the element at the front of the queue without altering the queue's state.

5. The main method demonstrates queue operations by creating a Queue instance, enqueuing elements, peeking at the front element, dequeuing elements, and then peeking again to show the state of the queue after some operations. This demonstrates the FIFO behavior of the queue, where elements are processed in the order they were added.

Comments