ArrayList in Java
An ArrayList in Java is a dynamic array that can grow and shrink in size as needed. It is a part of the Java Collections Framework and is located in the java.util package. ArrayLists are similar to arrays but offer more flexibility in terms of size management. They provide methods to add, remove, and access elements at specific positions efficiently.
Table of Contents
Here’s a breakdown of key points regarding ArrayList in Java:
1. Dynamic Size: Unlike traditional arrays in Java, ArrayLists can dynamically resize themselves to accommodate additional elements.
2. Random Access: ArrayLists provide constant-time access to elements using their index, similar to arrays.
3. Automatic Resizing: When the ArrayList reaches its capacity, it automatically increases its size to accommodate more elements.
4. Allows Duplicates: ArrayLists can contain duplicate elements.
5. Ordered Collection: Elements in an ArrayList maintain their insertion order.
Now, let’s provide a Java code example to illustrate the usage of ArrayList:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
// Adding elements to the ArrayList
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Accessing elements by index
System.out.println("Element at index 1: " + numbers.get(1)); // Output: 20
// Iterating through the ArrayList
System.out.println("ArrayList elements:");
for (int num : numbers) {
System.out.println(num);
}
// Adding an element at a specific index
numbers.add(1, 15); // Inserting 15 at index 1
// Removing an element
numbers.remove(2); // Removing element at index 2
// Checking if the ArrayList contains a certain element
System.out.println("Contains 30? " + numbers.contains(30)); // Output: false
// Getting the size of the ArrayList
System.out.println("Size of ArrayList: " + numbers.size()); // Output: 3
}
}
In this example, we create an ArrayList named numbers to store integers. We add elements to it using the add() method, access elements using the get() method, and iterate through the ArrayList using a for-each loop. Additionally, we demonstrate adding an element at a specific index with add(index, element), removing an element with remove(index), checking if the ArrayList contains a specific element with contains(), and getting the size of the ArrayList with size().