Java ArrayList
The ArrayList is a dynamic array implementation in Java that provides flexible size, type safety, and convenient methods for data manipulation. Unlike traditional arrays with fixed sizes, ArrayLists dynamically expand and shrink as elements are added or removed, providing more flexibility for data manipulation.
Syntax
The ArrayList class is part of the java.util package and must be imported before use:
import java.util.ArrayList;
Creating an ArrayList
There are three ways to initialize an ArrayList:
// Empty ArrayList with default initial capacity (10)ArrayList<DataType> list1 = new ArrayList<>();// Empty ArrayList with specified initial capacityArrayList<DataType> list2 = new ArrayList<>(initialCapacity);// ArrayList initialized with elements from another collectionArrayList<DataType> list3 = new ArrayList<>(collection);
Where:
DataTypeis the type of elements the ArrayList will holdinitialCapacityis the initial storage capacity of the ArrayListcollectionis another collection whose elements will be added to the ArrayList
Working with Primitive Types
ArrayList can only store objects, not primitive types. For primitives, use their wrapper classes:
| Primitive Type | Wrapper Class |
|---|---|
| boolean | Boolean |
| byte | Byte |
| char | Character |
| double | Double |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
For example, to create an ArrayList of integers:
ArrayList<Integer> numbers = new ArrayList<>();numbers.add(10); // Auto-boxing converts int to Integer
This process is called auto-boxing, where primitive values are automatically converted to their corresponding wrapper class.
Comparison with Other Collections
ArrayList has several important characteristics that distinguish it from other collection types:
| Feature | ArrayList | LinkedList | HashSet |
|---|---|---|---|
| Ordered | Yes | Yes | No |
| Allows Duplicates | Yes | Yes | No |
| Allows Nulls | Yes | Yes | Yes |
| Fast Random Access | Yes | No | N/A |
| Thread-Safe | No | No | No |
Example
In this example, a new ArrayList instance arr is defined. There are print statements throughout to show elements being added to and removed from arr before it is ultimately cleared:
// Import from the java.util packageimport java.util.ArrayList;public class Example {public static void main(String []args) {ArrayList<String> arr = new ArrayList<>();System.out.println(arr); // Currently emptyarr.add("hello");arr.add("India");System.out.println(arr);arr.remove("hello");System.out.println(arr.size()); // Prints size of ArrayListarr.clear();System.out.println(arr); // Empty again}}
The output would be:
[][hello, India]1[]
Frequently Asked Questions
1. What is the difference between ArrayList and LinkedList?
ArrayList is better for fast random access and low overhead; LinkedList is better for frequent insertions/deletions.
2. What is an ArrayList vs. array?
ArrayLists are dynamic and only hold objects. Arrays are fixed-size and can hold primitives or objects.
3. Does ArrayList allow duplicates?
Yes, it maintains insertion order and allows duplicate elements.
ArrayList
- .add()
- Adds an element to an ArrayList.
- .addAll()
- Adds a collection to an ArrayList.
- .clear()
- Removes all elements from an ArrayList.
- .clone()
- Returns a cloned version of the given ArrayList.
- .contains()
- Checks if an element is present in the ArrayList or not.
- .forEach()
- Performs a specified action on each element in an ArrayList.
- .get()
- Retrieves the element present in a specified position in an ArrayList.
- .indexOf()
- Returns the index of the first occurrence of a given element, or -1 if not found.
- .isEmpty()
- Checks if an ArrayList is empty.
- .iterator()
- Returns an iterator over the elements in an ArrayList.
- .listIterator()
- Iterates over the elements in an ArrayList in both directions.
- .remove()
- Removes a specified element from an ArrayList.
- .removeAll()
- Removes multiple elements from an ArrayList that are also contained in the specified collection.
- .removeIf()
- Removes all the elements of an ArrayList that satisfy a given predicate.
- .removeRange()
- Removes every element within a specified range.
- .replaceAll()
- Replaces each element in the ArrayList with the result of applying a specified unary operator to it.
- .retainAll()
- Retains only the elements that are contained in the specified collection.
- .set()
- Replaces the element present at a specified position with another element in an ArrayList.
- .size()
- Returns the number of elements in the ArrayList.
- .sort()
- Used to sort arrays of primitive types and objects.
- .spliterator()
- Returns a Spliterator over the elements in ArrayList.
- .subList()
- Returns a view of a portion of the list based on the specified start and end indices.
- .toArray()
- Converts an ArrayList into an array.
- .trimToSize()
- Adjusts the capacity of the ArrayList to be the same as its size.
All contributors
- Anonymous contributor
BrandonDusch- Anonymous contributor
- Anonymous contributor
- vivek_prajapatii
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours