The ArrayList class in Java is part of the java.util package and is one of the most commonly used collection classes. It provides a dynamic array implementation, allowing developers to store, access, and manipulate elements efficiently without worrying about the fixed size limitations of traditional arrays.
Key features of ArrayList include:
Dynamic Resizing: Unlike arrays, ArrayLists automatically grow or shrink as elements are added or removed.
Ordered Collection: Maintains the insertion order of elements.
Duplicate Elements: Allows duplicate values, making it versatile for various use cases.
Generics Support: Allows developers to specify the type of elements it will store, improving type safety and reducing runtime errors.
Convenience Methods: Provides a wide range of methods for adding, removing, searching, and modifying elements.
Here’s a simple example of creating and using an ArrayList:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList to store strings
ArrayList<String> fruits = new ArrayList<>();
// Add elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Display the ArrayList
System.out.println("Fruits: " + fruits);
// Access an element
System.out.println("First Fruit: " + fruits.get(0));
// Remove an element
fruits.remove("Banana");
System.out.println("After Removal: " + fruits);
}
}
Below are the frequently used methods:
Method | Description |
add() | Adds an element to the list. |
remove() | Removes an element by value or index. |
size() | Returns the number of elements in the list. |
get() | Retrieves an element by index. |
set() | Updates the element at a specific index. |
contains() | Checks if the list contains a specific value. |
These methods provide the foundation for working with ArrayLists and are essential for efficient data manipulation in Java programs.
1. add()
Method
The add()
method is used to insert elements into the ArrayList. It can add elements at the end of the list or at a specific index.
Example:
import java.util.ArrayList;
public class AddExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple"); // Add at the end
list.add("Banana");
list.add(1, "Cherry"); // Add at index 1
System.out.println("List after adding elements: " + list);
}
}
Output:
List after adding elements: [Apple, Cherry, Banana]
2. remove()
Method
The remove()
method is used to delete elements by index or value.
Example:
import java.util.ArrayList;
public class RemoveExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.remove(1); // Remove element at index 1
System.out.println("After removing by index: " + list);
list.remove("Cherry"); // Remove element by value
System.out.println("After removing by value: " + list);
}
}
Output:
After removing by index: [Apple, Cherry]
After removing by value: [Apple]
3. size()
Method
The size()
method returns the number of elements in the ArrayList.
Example:
import java.util.ArrayList;
public class SizeExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println("Size of the list: " + list.size());
}
}
Output:
Size of the list: 2
4. get()
Method
The get()
method retrieves an element from the specified index.
Example:
import java.util.ArrayList;
public class GetExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println("Element at index 0: " + list.get(0));
}
}
Output:
Element at index 0: Apple
5. set()
Method
The set()
method replaces the element at a specific index with a new value.
Example:
import java.util.ArrayList;
public class SetExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.set(1, "Cherry"); // Replace element at index 1
System.out.println("List after modification: " + list);
}
}
Output:
List after modification: [Apple, Cherry]
6. contains()
Method
The contains()
method checks if the ArrayList contains a specific element. It returns true
or false
.
Example:
import java.util.ArrayList;
public class ContainsExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println("Contains 'Apple': " + list.contains("Apple"));
System.out.println("Contains 'Cherry': " + list.contains("Cherry"));
}
}
Output:
Contains 'Apple': true
Contains 'Cherry': false
Iterating through an ArrayList in Java
Java provides multiple ways to iterate over the elements of an ArrayList. Each method has its own advantages, and the choice of iteration depends on the specific requirements of your application. Let's explore the most common ways to iterate through an ArrayList.
Table of Iteration Methods
Method | Description |
For Loop | Classic approach using index-based iteration. |
Enhanced For Loop | Simplified loop for iterating over elements directly (no index). |
Iterator | Allows iteration with the option to remove elements safely during iteration. |
ListIterator | Similar to Iterator , but supports both forward and backward iteration. |
Java 8 Streams | Functional programming approach for processing elements, supporting filters, maps, etc. |
1 . Using a For Loop
A traditional for
loop is one of the most basic ways to iterate through an ArrayList. It allows you to access elements by their index.
Example:
import java.util.ArrayList;
public class ForLoopExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (int i = 0; i < list.size(); i++) {
System.out.println("Element at index " + i + ": " + list.get(i));
}
}
}
Output:
Element at index 0: Apple
Element at index 1: Banana
Element at index 2: Cherry
2. Using an Enhanced For Loop (for-each loop)
The enhanced for
loop simplifies the process of iterating over the elements without needing to deal with indices. It's especially useful when you don't need to modify the list or track the index.
Example:
import java.util.ArrayList;
public class EnhancedForLoopExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String item : list) {
System.out.println(item);
}
}
}
Output:
Apple
Banana
Cherry
3. Using an Iterator
The Iterator
is an interface that provides methods to iterate through a collection. It is particularly useful when you need to remove elements while iterating.
Example:
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
Apple
Banana
Cherry
Note:
The Iterator
also provides the remove()
method, allowing you to safely remove elements from the list during iteration.
4. Using a ListIterator
The ListIterator
is a more powerful version of the Iterator
, as it allows you to iterate in both forward and backward directions, and also modify the list during iteration.
Example:
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
ListIterator<String> listIterator = list.listIterator();
// Iterate forward
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// Iterate backward
System.out.println("Iterating backward:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
Output:
Apple
Banana
Cherry
Iterating backward:
Cherry
Banana
Apple
5. Using Java 8 Streams
With Java 8 and later, Streams provide a functional way to iterate through collections. Streams allow operations like filtering, mapping, and reducing, making it powerful for processing data.
Example:
import java.util.ArrayList;
public class StreamsExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Using forEach with Stream
list.stream().forEach(item -> System.out.println(item));
}
}
Output:
CopyEditApple
Banana
Cherry
Explanation:
list.stream()
creates a Stream from the ArrayList..forEach(item -> System.out.println(item))
processes each element using the lambda expression.
we can also apply filters or transformations with Streams, such as:
list.stream().filter(item -> item.startsWith("A")).forEach(System.out::println);
This would only print elements that start with the letter "A".
To read Sorting an ArrayList - Visit https://sdetinsider.hashnode.dev/sorting-an-arraylist