Introduce Java ArrayList and give examples
In Java, an ArrayList
is part of the Java Collections Framework and is a resizable array implementation of the List
interface. It allows for dynamic arrays that can grow as needed to accommodate new elements. Unlike arrays, which have a fixed size, ArrayList
can change its size automatically when elements are added or removed.
Here are some common operations you can perform with an ArrayList
:
Here’s a simple example demonstrating the use of ArrayList
in Java:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// 1. Creating an ArrayList
ArrayList<String> fruits = new ArrayList<>();
// 2. Adding Elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
fruits.add("Elderberry");
// 3. Accessing Elements
System.out.println("First fruit: " + fruits.get(0)); // Output: Apple
System.out.println("Second fruit: " + fruits.get(1)); // Output: Banana
// 4. Removing Elements
fruits.remove("Date"); // Removes "Date"
System.out.println("After removing Date: " + fruits);
// 5. Iterating Over Elements
System.out.println("List of fruits:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// 6. Checking Size and Emptiness
System.out.println("Total number of fruits: " + fruits.size()); // Output: 4
System.out.println("Is the list empty? " + fruits.isEmpty()); // Output: false
// 7. Clearing the ArrayList
fruits.clear();
System.out.println("After clearing, is the list empty? " + fruits.isEmpty()); // Output: true
}
}
ArrayList
named fruits
to store String
elements.add()
method to add fruits to the list.get()
method with an index.remove()
method.size()
to get the number of elements and isEmpty()
to check if the list is empty.clear()
method to remove all elements from the list.ArrayList
is a powerful and flexible data structure in Java that is widely used for storing and manipulating lists of objects. Its dynamic nature and built-in methods make it a popular choice for many programming tasks.