An ArrayList
is one of the most commonly used classes in Java for storing data. It belongs to the java.util
package and implements the List
interface. Unlike arrays, which have a fixed size, ArrayList
can dynamically resize itself as elements are added or removed.
Features
- Dynamic Size: Unlike arrays, which have a fixed size,
ArrayList
grows or shrinks as needed when elements are added or removed. - Ordered Collection: Elements in an
ArrayList
are ordered, meaning they maintain the insertion order. - Index-based Access: You can access elements in an
ArrayList
using an index, similar to arrays. Indexing starts from 0. - Null Elements:
ArrayList
allowsnull
values, which is not allowed in some other collections.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { // Create an ArrayList of Strings ArrayList<String> fruits = new ArrayList<>(); // Adding elements to the ArrayList fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add("Mango"); System.out.println("ArrayList after adding elements: " + fruits); // Accessing elements using the get() method String firstFruit = fruits.get(0); System.out.println("First fruit: " + firstFruit); // Modifying elements using the set() method fruits.set(1, "Blueberry"); System.out.println("ArrayList after modifying element at index 1: " + fruits); // Removing elements using remove() method (by index and value) fruits.remove(2); // Removes "Orange" fruits.remove("Mango"); // Removes "Mango" System.out.println("ArrayList after removing elements: " + fruits); // Checking the size of the ArrayList int size = fruits.size(); System.out.println("Size of ArrayList: " + size); // Iterating through the ArrayList using a for-each loop System.out.println("Iterating through the ArrayList:"); for (String fruit : fruits) { System.out.println(fruit); } } } //Output ArrayList after adding elements: [Apple, Banana, Orange, Mango] First fruit: Apple ArrayList after modifying element at index 1: [Apple, Blueberry, Orange, Mango] ArrayList after removing elements: [Apple, Blueberry, Mango] Size of ArrayList: 3 Iterating through the ArrayList: Apple Blueberry Mango |
Use Cases
- Dynamic Data Storage: When you need a collection that can grow or shrink as needed, such as storing user input or dynamic data like orders in an e-commerce app.
- Implementing Lists of Items: For example, maintaining a list of players in a team, where the number of players can change.
- Data Manipulation: ArrayLists are useful for sorting, filtering, and modifying collections of data in real-time.
- Performance Sensitivity: When fast random access to elements is needed,
ArrayList
is preferred overLinkedList
, as it offers O(1) time complexity for get operations.