In Java, an ArrayList
is a dynamic array that can grow or shrink in size as needed. It is part of the java.util
package and provides methods to add, remove, and access elements in the array.
Here’s an example that demonstrates how to use an ArrayList
:
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { // Create an ArrayList of integers ArrayList<Integer> numbers = new ArrayList<>(); // Add elements to the ArrayList numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); // Get the size of the ArrayList int size = numbers.size(); System.out.println("Size of ArrayList: " + size); // Access elements in the ArrayList int firstElement = numbers.get(0); int thirdElement = numbers.get(2); System.out.println("First element: " + firstElement); System.out.println("Third element: " + thirdElement); // Modify an element in the ArrayList numbers.set(1, 25); System.out.println("Modified ArrayList: " + numbers); // Remove an element from the ArrayList numbers.remove(3); System.out.println("ArrayList after removing an element: " + numbers); // Check if an element is present in the ArrayList boolean contains = numbers.contains(20); System.out.println("ArrayList contains 20: " + contains); // Iterate over the elements in the ArrayList for (int i = 0; i < numbers.size(); i++) { int element = numbers.get(i); System.out.println("Element at index " + i + ": " + element); } // Clear the ArrayList numbers.clear(); System.out.println("ArrayList after clearing all elements: " + numbers); } }
In this example, we create an ArrayList
of integers using the ArrayList
class and add four elements to it using the add()
method. We then use the size()
method to get the size of the ArrayList and the get()
method to access the first and third elements.
We also demonstrate how to modify an element using the set()
method, remove an element using the remove()
method, check if an element is present in the ArrayList using the contains()
method, and iterate over the elements using a for loop.
Finally, we use the clear()
method to remove all elements from the ArrayList.
The output of this example might look something like this:
Size of ArrayList: 4 First element: 10 Third element: 30 Modified ArrayList: [10, 25, 30, 40] ArrayList after removing an element: [10, 25, 30] ArrayList contains 20: false Element at index 0: 10 Element at index 1: 25 Element at index 2: 30 ArrayList after clearing all elements: []
ArrayList
provides several advantages over traditional arrays, including the ability to resize dynamically and the convenience of built-in methods for adding, removing, and accessing elements. However, ArrayList
can be less efficient than arrays when it comes to certain operations, such as random access and insertion at the beginning or middle of the list.