The ArrayList is a fundamental data structure in Java, providing a resizable array implementation of the List Interface. It offers dynamic sizing and efficient element manipulation, making it a versatile choice for many programming tasks.
ArrayList is part of the Java Collections Framework. It stores elements in a dynamic array, allowing for flexible size adjustments as elements are added or removed. This class is ideal when you need a growable list of objects with fast access times.
To use ArrayList, you first need to import it from the java.util package. Here's how to create an ArrayList:
import java.util.ArrayList;
// Creating an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();
// Creating an ArrayList with initial capacity
ArrayList<Integer> numbers = new ArrayList<>(10);
Use the add()
method to append elements to the ArrayList:
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
Retrieve elements using the get()
method with the index:
String firstFruit = fruits.get(0); // Returns "Apple"
Update elements using the set()
method:
fruits.set(1, "Blueberry"); // Replaces "Banana" with "Blueberry"
Remove elements using the remove()
method:
fruits.remove("Cherry");
// or
fruits.remove(0); // Removes the first element
Method | Description |
---|---|
size() |
Returns the number of elements in the list |
clear() |
Removes all elements from the list |
contains(Object o) |
Returns true if the list contains the specified element |
indexOf(Object o) |
Returns the index of the first occurrence of the specified element |
toArray() |
Converts the ArrayList to an array |
There are several ways to iterate through an ArrayList. Here are two common methods:
for (String fruit : fruits) {
System.out.println(fruit);
}
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
While both ArrayList and arrays store elements, they have some key differences:
Collections.synchronizedList()
for thread-safe operationstrimToSize()
to reduce memory usage after removing elementsArrayList is a powerful and flexible data structure in Java. Its dynamic sizing and rich set of methods make it suitable for a wide range of applications. By understanding its features and best practices, you can effectively use ArrayList to write more efficient and maintainable Java code.