What is ArrayList?
An ArrayList is a special kind of list that can store multiple items and change its size automatically.
Regular arrays have a fixed length, but an ArrayList can grow or shrink as you add or remove elements.
It is part of Java.util package and is a key part of Javaโs Collections Framework.
Imagine it’s a resizable basket where you can put items in (add), take items out (remove) and check what’s inside (get), without worrying about the basket being too small or too big.
Why Use an ArrayList?
- Dynamic Size: ArrayList can automatically adjust its size when you add or remove elements.
- Easy to Use: It offers methods like add(), remove(), get(), set(), size().
- Part of Java Collections Framework: It easily works with Java sorting and iteration.
How to Use ArrayList
1. Import the ArrayList Class
First, we will import ArrayList class from the java.util package.
import java.util.ArrayList;
2. Create an ArrayList
You can create an ArrayList to store any type of objects using generics. For example:
ArrayList<String> names = new ArrayList<>(); // Stores strings
ArrayList<Integer> numbers = new ArrayList<>(); // Stores integers
ArrayList<Double> marks = new ArrayList<>(); // Stores decimal numbers
3. Add Elements to ArrayList
names.add("Alice");
names.add("Bob");
numbers.add(10);
numbers.add(20);
4. Access Elements from ArrayList
System.out.println("First name: " + names.get(0)); // Access first element
Common Methods of ArrayList
- add(E element)
- add(int index, E element)
- remove(int index)
- get(int index)
- set(int index, E element)
- size()
- clear()
- contains(Object o)
- isEmpty()
Examples of Using ArrayList
You can perform add, update, remove, and access operations easily with ArrayList.
1. Basic Operations
import java.util.ArrayList;
public class FruitsExample {
public static void main(String[] args) {
// Create an ArrayList to store fruits
ArrayList<String> fruits = new ArrayList<>();
// Add elements
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Grapes");
// Display the list
System.out.println("Fruits List: " + fruits);
// Access an element by index
System.out.println("First fruit: " + fruits.get(0));
// Remove an element by value
fruits.remove("Mango");
System.out.println("After removing Mango: " + fruits);
// Update an element
fruits.set(1, "Banana"); // Replace Grapes with Banana
System.out.println("After update: " + fruits);
// Check the size
System.out.println("Total fruits: " + fruits.size());
}
}
Output:
Fruits List: [Apple, Mango, Grapes]
First fruit: Apple
After removing Mango: [Apple, Grapes]
After update: [Apple, Banana]
Total fruits: 2
2. Iterating Through an ArrayList
You can loop through an ArrayList to read all elements.
Using a For-Each Loop
for (String fruit : fruits) {
System.out.println(fruit);
}
Using a For Loop
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
3. Working with Integer ArrayList
ArrayLists are not limited to strings, they can store numbers. For example:
import java.util.ArrayList;
public class NumbersExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Add numbers
numbers.add(5);
numbers.add(15);
numbers.add(25);
// Display numbers
System.out.println("Numbers: " + numbers);
// Calculate sum of numbers
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum);
}
}
Output:
Numbers: [5, 15, 25]
Sum: 45
4. Sorting an ArrayList
We can use Collections.sort() to sort lists easily. For example:
import java.util.ArrayList;
import java.util.Collections;
public class SortExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Zara");
names.add("Liam");
names.add("Emma");
// Sort the list alphabetically
Collections.sort(names);
System.out.println("Sorted Names: " + names);
}
}
Output:
Sorted Names: [Emma, Liam, Zara]
ArrayList is not synchronized, which means multiple threads modifying it at the same time can cause unexpected results.
If you need thread safety, you can use:
List<String> safeList = Collections.synchronizedList(new ArrayList<>());
Mini Project: Student Attendance Tracker
Create a simple program to track student attendance for a class. You can add students, mark attendance, view present students, and calculate attendance percentage.
Code example:
import java.util.ArrayList;
import java.util.Scanner;
class Student {
String name;
int daysPresent;
Student(String name) {
this.name = name;
this.daysPresent = 0; // initially 0
}
}
public class AttendanceTracker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int totalDays = 0;
boolean running = true;
while (running) {
System.out.println("\n--- Attendance Tracker ---");
System.out.println("1. Add Student");
System.out.println("2. Mark Attendance");
System.out.println("3. View Attendance");
System.out.println("4. View Attendance Percentage");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline
switch (choice) {
case 1:
System.out.print("Enter student name: ");
String name = scanner.nextLine();
students.add(new Student(name));
System.out.println("Student added successfully!");
break;
case 2:
if (students.isEmpty()) {
System.out.println("No students to mark attendance for!");
break;
}
totalDays++;
System.out.println("Mark attendance for day " + totalDays);
for (Student s : students) {
System.out.print("Is " + s.name + " present? (y/n): ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("y")) {
s.daysPresent++;
}
}
System.out.println("Attendance marked for day " + totalDays);
break;
case 3:
System.out.println("\n--- Attendance Record ---");
for (Student s : students) {
System.out.println(s.name + ": " + s.daysPresent + " days present");
}
break;
case 4:
System.out.println("\n--- Attendance Percentage ---");
for (Student s : students) {
double percentage = totalDays == 0 ? 0 : (s.daysPresent * 100.0) / totalDays;
System.out.printf("%s: %.2f%%\n", s.name, percentage);
}
break;
case 5:
running = false;
System.out.println("Exiting... Thank you!");
break;
default:
System.out.println("Invalid option! Try again.");
}
}
scanner.close();
}
}
Output:
--- Attendance Tracker ---
1. Add Student
2. Mark Attendance
3. View Attendance
4. View Attendance Percentage
5. Exit
Choose an option: 1
Enter student name: Alice
Student added successfully!
Choose an option: 1
Enter student name: Bob
Student added successfully!
Choose an option: 2
Mark attendance for day 1
Is Alice present? (y/n): y
Is Bob present? (y/n): n
Attendance marked for day 1
Choose an option: 4
--- Attendance Percentage ---
Alice: 100.00%
Bob: 0.00%
- Write this logic by yourself, and keep practicing of Java ArrayList.
Also Learn Important Topics of Java
- What are the operators in Java Programming?
- What are Data Types in Java?
- What are the Variables in Java?
- Learn Java syntax.
- What is Java if else statements?
- What is method overloading in Java?
- What are the Classes and Objects in Java?
- What is Polymorphism in Java?
- What is Interfaces in Java?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.