Problem Statement: Write a Java program to create an ArrayList of integers, add elements, remove elements, and find the size of the list.
Here’s a Java program that demonstrates how to create an ArrayList
of integers, add elements to it, remove elements from it, and find the size of the list. I’ll provide a thorough explanation of the logic behind each step.
package com.javacodepoint.collection;
import java.util.ArrayList;
public class ArrayListManipulation {
public static void main(String[] args) {
// Create an ArrayList to store integers
ArrayList<Integer> numbers = new ArrayList<>();
// Adding elements to the ArrayList
numbers.add(10); // Add the integer 10 to the list
numbers.add(20); // Add the integer 20 to the list
numbers.add(30); // Add the integer 30 to the list
System.out.println("ArrayList after adding elements: " + numbers);
// Removing an element from the ArrayList
numbers.remove(1); // Remove the element at index 1 (20)
System.out.println("ArrayList after removing element at index 1: " + numbers);
// Finding the size of the ArrayList
int size = numbers.size(); // Get the number of elements in the list
System.out.println("Size of the ArrayList: " + size);
}
}
OUTPUT:
ArrayList after adding elements: [10, 20, 30]
ArrayList after removing element at index 1: [10, 30]
Size of the ArrayList: 2
Explanation:
- Import Statement: The
import
statement is used to import the necessary classes. In this case, we’re importing theArrayList
class from thejava.util
package. - Creating an ArrayList: We create an
ArrayList
namednumbers
that will store integers. We specify the type of elements the list will hold using the angle brackets (<>
) and the type parameter (Integer
in this case). - Adding Elements: We use the
add()
method to add integers to thenumbers
list. We add three integers: 10, 20, and 30. Theadd()
method appends elements to the end of the list. - Printing the ArrayList: We use the
System.out.println()
statement to print the contents of thenumbers
list after adding the elements. - Removing an Element: We use the
remove()
method to remove an element from the list. In this case, we remove the element at index 1, which is the integer 20. - Printing the Modified ArrayList: We print the contents of the
numbers
list again after removing the element at index 1. - Finding the Size: We use the
size()
method to find the number of elements in thenumbers
list. The result is stored in thesize
variable. - Printing the Size: We print the size of the
numbers
list using theSystem.out.println()
statement.
By following these steps, the program demonstrates how to create an ArrayList
of integers, add elements to it, remove elements from it, and find the size of the list. This is a fundamental example of working with collections in Java.
See also: List Manipulation: Reverse a List.