ArrayList is a resizable array implementation of the List interface. Has the capability to grow automatically.
The ArrayList in Java is a part of the Java Collections Framework and is present in java.util package. Unlike Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.
Key Points about Java ArrayList
Dynamic Array: ArrayList is essentially a dynamic array that can grow or shrink in size.
Implements List Interface: It implements the List interface of the Java Collections Framework.
Not Synchronized: ArrayList is not synchronized (or thread-safe) by default.
Supports Duplicate Elements: It can contain duplicate elements.
Maintains Insertion Order: ArrayList maintains the order of elements based on their insertion order.
Allows Null Elements: You can add null to an ArrayList.
Random Access: Provides fast random access because of the underlying array.
Variable Size: Its capacity grows automatically when more elements are added.
Performance: ArrayList provides constant-time performance for basic operations (get and set) but linear-time performance for add or remove with index due to shifts.
Fail-Fast: Its iterators are fail-fast. If the ArrayList is modified after an iterator is created (except through the iterator’s own methods), it will throw a ConcurrentModificationException.
Methods: Provides numerous methods to manipulate (add, remove, find, etc.) elements.
Supports Generics: You can use generics to ensure type safety.
Backed by Array: Internally uses an array to store elements. When the array gets full, it gets resized.
1. Create an ArrayList and Add New Elements to it
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// Creating an ArrayList of Strings to store fruit names
ArrayList<String> fruits = new ArrayList<>();
// Adding fruits to the ArrayList using add() method
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
// Printing the ArrayList
System.out.println(fruits);
}
}
Output:
[Mango, Apple, Banana, Grapes]
ArrayList(): This is the default constructor of the ArrayList class. It creates an empty list.
add(E element): This method is used to append the specified element to the end of a list.
System.out.println(): This is used to print objects to the standard output (console).
2. Create an Arraylist from Another ArrayList
import java.util.ArrayList;
public class ArrayListFromArrayListDemo {
public static void main(String[] args) {
// Step 1: Creating the first ArrayList of fruits
ArrayList<String> originalFruits = new ArrayList<>();
originalFruits.add("Mango");
originalFruits.add("Apple");
originalFruits.add("Banana");
// Creating a new ArrayList from the original ArrayList
ArrayList<String> newFruitList = new ArrayList<>(originalFruits);
System.out.println("New ArrayList after creation from original ArrayList: " + newFruitList);
// Step 2: Adding more fruits to the new ArrayList
ArrayList<String> additionalFruits = new ArrayList<>();
additionalFruits.add("Grapes");
additionalFruits.add("Orange");
additionalFruits.add("Pineapple");
// Using addAll() method to add all the fruits from additionalFruits to newFruitList
newFruitList.addAll(additionalFruits);
System.out.println("New ArrayList after adding more fruits: " + newFruitList);
}
}
Output:
New ArrayList after creation from original ArrayList: [Mango, Apple, Banana]
New ArrayList after adding more fruits: [Mango, Apple, Banana, Grapes, Orange, Pineapple]
The addAll() method is utilized to append all elements from a collection to the end of an ArrayList.
3. Access Elements From an ArrayList
import java.util.ArrayList;
public class AccessElementsDemo {
public static void main(String[] args) {
// Creating an ArrayList of fruits
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
// 1. Checking if ArrayList is empty using isEmpty() method
boolean isEmpty = fruits.isEmpty();
System.out.println("Is the ArrayList empty? " + isEmpty);
// 2. Finding the size of ArrayList using size() method
int size = fruits.size();
System.out.println("Size of the ArrayList: " + size);
// 3. Accessing element at a particular index using get() method
String fruitAtIndex2 = fruits.get(2);
System.out.println("Fruit at index 2: " + fruitAtIndex2);
// 4. Modifying element at a particular index using set() method
fruits.set(2, "Orange");
System.out.println("ArrayList after modifying element at index 2: " + fruits);
}
}
Output:
Is the ArrayList empty? false
Size of the ArrayList: 4
Fruit at index 2: Banana
ArrayList after modifying element at index 2: [Mango, Apple, Orange, Grapes]
The isEmpty() method returns a boolean value indicating whether the ArrayList is empty (true) or contains elements (false).
The size() method returns the number of elements present in the ArrayList.
The get(int index) method is used to fetch an element from the specified index of the ArrayList. It’s important to remember that ArrayList uses zero-based indexing.
The set(int index, E element) method replaces the element at the specified position with the new element. It’s an efficient way to update an element.
4. Remove Elements from an ArrayList
import java.util.ArrayList;
import java.util.Arrays;
public class RemoveElementsDemo {
public static void main(String[] args) {
// Creating an ArrayList of fruits
ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Mango", "Apple", "Banana", "Grapes", "Orange"));
// 1. Removing element at a given index using remove(int index) method
fruits.remove(1); // Removes "Apple"
System.out.println("ArrayList after removing element at index 1: " + fruits);
// 2. Removing an element using remove(Object o) method
fruits.remove("Banana");
System.out.println("ArrayList after removing 'Banana': " + fruits);
// 3. Removing all elements that exist in a given collection using removeAll() method
ArrayList<String> toRemove = new ArrayList<>(Arrays.asList("Mango", "Grapes"));
fruits.removeAll(toRemove);
System.out.println("ArrayList after removing elements from another collection: " + fruits);
// 4. Removing all elements matching a given predicate using removeIf() method
fruits.removeIf(fruit -> fruit.startsWith("O")); // Removes "Orange"
System.out.println("ArrayList after removing elements starting with 'O': " + fruits);
// 5. Clearing all elements in the ArrayList using clear() method
fruits.clear();
System.out.println("ArrayList after clearing all elements: " + fruits);
}
}
Output:
ArrayList after removing element at index 1: [Mango, Banana, Grapes, Orange]
ArrayList after removing 'Banana': [Mango, Grapes, Orange]
ArrayList after removing elements from another collection: [Orange]
ArrayList after removing elements starting with 'O': []
ArrayList after clearing all elements: []
remove(int index): This method removes the element at the specified index from the ArrayList.
remove(Object o): This method removes the first occurrence of the specified element from the ArrayList if it exists.
removeAll(Collection<?> c): This method removes from the ArrayList all of its elements that are also present in the specified collection.
removeIf(Predicate<? super E> filter): Removes all elements of the ArrayList that satisfy the given predicate.
clear(): This method removes all elements from the ArrayList.
5. Iterate over an ArrayList – Different Ways
Java 8 forEach with lambda: This is a concise way to iterate over each element in the list and perform an action. In our case, we’re printing each fruit.
iterator(): This provides an iterator over the list, and you can then traverse the list using the hasNext() and next() methods.
iterator() with forEachRemaining(): Java 8 introduced the forEachRemaining() method for iterators which is a combination of iterator and forEach.
listIterator(): Similar to the iterator, but ListIterator has more functionalities like adding an element, replacing an element, or iterating in reverse order.
Simple for-each loop: This is the enhanced for loop introduced in Java 5, which is a simpler way to iterate over all the elements of a list.
For loop with index: This is the traditional way to iterate using an index to get each element from the list.
Here is the complete example that demonstrates different ways to iterate over an ArrayList:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;
public class IterateArrayListDemo {
public static void main(String[] args) {
// Creating an ArrayList of fruits
ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Mango", "Apple", "Banana", "Grapes", "Orange"));
// 1. Using Java 8 forEach and lambda expression
System.out.println("Using Java 8 forEach with lambda:");
fruits.forEach(fruit -> System.out.println(fruit));
// 2. Using iterator()
System.out.println("\nUsing iterator():");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// 3. Using iterator() and Java 8 forEachRemaining() method
System.out.println("\nUsing iterator() with forEachRemaining():");
iterator = fruits.iterator();
iterator.forEachRemaining(fruit -> System.out.println(fruit));
// 4. Using listIterator()
System.out.println("\nUsing listIterator():");
ListIterator<String> listIterator = fruits.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// 5. Using simple for-each loop
System.out.println("\nUsing simple for-each loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// 6. Using for loop with index
System.out.println("\nUsing for loop with index:");
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
}
}
Output:
Using Java 8 forEach with lambda:
Mango
Apple
Banana
Grapes
Orange
Using iterator():
Mango
Apple
Banana
Grapes
Orange
Using iterator() with forEachRemaining():
Mango
Apple
Banana
Grapes
Orange
Using listIterator():
Mango
Apple
Banana
Grapes
Orange
Using simple for-each loop:
Mango
Apple
Banana
Grapes
Orange
Using for loop with index:
Mango
Apple
Banana
Grapes
Orange
6. Search Elements in an ArrayList
contains(): This method checks if the specified element is present in the list. It returns true if found, otherwise false.
indexOf(): This method returns the index of the first occurrence of the specified element in the list. If the element is not present, it returns -1.
lastIndexOf(): This method returns the index of the last occurrence of the specified element.
import java.util.ArrayList;
import java.util.Arrays;
public class SearchArrayListDemo {
public static void main(String[] args) {
// Creating an ArrayList of fruits
ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Mango", "Apple", "Banana", "Grapes", "Orange", "Apple"));
// Check if an ArrayList contains a given element using contains()
boolean containsApple = fruits.contains("Apple");
System.out.println("Does the list contain 'Apple'? " + containsApple);
// Find the index of the first occurrence of an element in an ArrayList using indexOf()
int firstIndexOfApple = fruits.indexOf("Apple");
System.out.println("Index of first occurrence of 'Apple': " + firstIndexOfApple);
// Find the index of the last occurrence of an element in an ArrayList using lastIndexOf()
int lastIndexOfApple = fruits.lastIndexOf("Apple");
System.out.println("Index of last occurrence of 'Apple': " + lastIndexOfApple);
}
}
Output:
Does the list contain 'Apple'? true
Index of first occurrence of 'Apple': 1
Index of last occurrence of 'Apple': 5
7. ArrayList with User-Defined Objects
Here’s an example that demonstrates using an ArrayList to store custom objects. In this case, the custom object is a Student.
Step 1: Define the Student class.
public class Student {
private int id;
private String name;
private double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getGrade() {
return grade;
}
@Override
public String toString() {
return "Student[ID: " + id + ", Name: " + name + ", Grade: " + grade + "]";
}
}
Step 2: Create an ArrayList of Student objects and add some students.
import java.util.ArrayList;
public class StudentListDemo {
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<>();
// Adding students to the list
studentList.add(new Student(1, "Amit", 85.5));
studentList.add(new Student(2, "Rohit", 90.0));
studentList.add(new Student(3, "Priya", 92.5));
// Displaying the students in the list
for (Student student : studentList) {
System.out.println(student);
}
}
}
Output:
Student[ID: 1, Name: Amit, Grade: 85.5]
Student[ID: 2, Name: Rohit, Grade: 90.0]
Student[ID: 3, Name: Priya, Grade: 92.5]
8. Sort an ArrayList
Sort an ArrayList using Collections.sort() method:
This method sorts an ArrayList
in ascending order by default.
import java.util.ArrayList;
import java.util.Collections;
public class SortingExample1 {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Banana");
Collections.sort(fruits);
System.out.println(fruits); // Output: [Apple, Banana, Mango]
}
}
Sort an ArrayList using ArrayList.sort() method:
This method was introduced in Java 8 and it’s based on the list’s natural ordering or with a provided comparator.
import java.util.ArrayList;
public class SortingExample2 {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Banana");
fruits.sort(null); // This sorts using the natural ordering
System.out.println(fruits); // Output: [Apple, Banana, Mango]
}
}
Sort an ArrayList of user-defined objects with a custom comparator:
When you have a list of custom objects, you’ll need a Comparator to define how the sorting should be done.
import java.util.ArrayList;
import java.util.Comparator;
public class SortingExample3 {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(1, "Amit", 85.5));
students.add(new Student(2, "Rohit", 90.0));
students.add(new Student(3, "Priya", 92.5));
// Sort students by their grades using a custom comparator
students.sort(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Double.compare(s1.getGrade(), s2.getGrade());
}
});
// Display the sorted list of students
for (Student student : students) {
System.out.println(student);
}
// Output will have students sorted by their grades in ascending order
}
}
9. Synchronize Access to an ArrayList
Synchronizing access to an ArrayList is important when multiple threads are involved, as ArrayList is not thread-safe by default. If multiple threads modify an ArrayList concurrently, and at least one of the threads modifies it structurally, it must be synchronized externally.
The Collections.synchronizedList() method provides a way to synchronize an ArrayList:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SynchronizedArrayListExample {
public static void main(String[] args) {
List<String> syncList = Collections.synchronizedList(new ArrayList<String>());
// Adding elements
syncList.add("Amit");
syncList.add("Rohit");
syncList.add("Priya");
// Synchronized block to iterate over synchronized list
synchronized (syncList) {
for (String str : syncList) {
System.out.println(str);
}
}
// You can also have other synchronized operations
// For example: removing an item
synchronized (syncList) {
syncList.remove("Rohit");
}
System.out.println("After removing Rohit:");
synchronized (syncList) {
for (String str : syncList) {
System.out.println(str);
}
}
}
}
Output:
Amit
Rohit
Priya
After removing Rohit:
Amit
Priya
10. Real-World Example: Library Management
Imagine you’re building a simple library management system. The library contains a collection of books. For simplicity, each book has a title and an author.
Step 1: Define the Book class.
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return "Book{title='" + title + "', author='" + author + "'}";
}
}
Step 2: Use ArrayList to manage a collection of books.
public class Library {
private ArrayList<Book> books = new ArrayList<>();
// Add a book to the library.
public void addBook(Book book) {
books.add(book);
}
// Remove a book from the library.
public void removeBook(Book book) {
books.remove(book);
}
// Find a book by its title.
public Book findBookByTitle(String title) {
for (Book book : books) {
if (book.toString().contains(title)) {
return book;
}
}
return null;
}
// Display all books in the library.
public void displayBooks() {
for (Book book : books) {
System.out.println(book);
}
}
public static void main(String[] args) {
Library myLibrary = new Library();
// Adding books
myLibrary.addBook(new Book("To Kill a Mockingbird", "Harper Lee"));
myLibrary.addBook(new Book("The Great Gatsby", "F. Scott Fitzgerald"));
myLibrary.addBook(new Book("1984", "George Orwell"));
System.out.println("Books in the library:");
myLibrary.displayBooks();
// Output:
// Book{title='To Kill a Mockingbird', author='Harper Lee'}
// Book{title='The Great Gatsby', author='F. Scott Fitzgerald'}
// Book{title='1984', author='George Orwell'}
// Removing a book
Book bookToRemove = myLibrary.findBookByTitle("1984");
if (bookToRemove != null) {
myLibrary.removeBook(bookToRemove);
}
System.out.println("\nBooks after removing '1984':");
myLibrary.displayBooks();
// Output:
// Book{title='To Kill a Mockingbird', author='Harper Lee'}
// Book{title='The Great Gatsby', author='F. Scott Fitzgerald'}
}
}
This example showcases how an ArrayList can be efficiently used in real-world applications to store, manage, and retrieve data. The library management system is a simple representation, and actual systems could be more complex and sophisticated, but this provides a basic idea of how one might use ArrayList in practice.
Conclusion
In this tutorial, you learned what is an ArrayList, key points about ArrayList, how to create an ArrayList, how to add, modify, and remove elements from an ArrayList, how to iterate over an ArrayList, how to sort an ArrayList, how to synchronize access to an ArrayList and a real-world example of ArrayList. Thank you for reading. See you in the next tutorial.