Introduction to ArrayList in Java ๐
When beginners start learning Java, they usually begin with arrays. Arrays are powerful, but they come with a major limitation โ fixed size. Once an array is created, its size cannot be changed.
This is where ArrayList comes into the picture ๐ก.
An ArrayList is a part of Javaโs Collection Framework and provides a dynamic array, meaning it can grow and shrink automatically during runtime. It makes Java programming more flexible, readable, and efficient.
This article will explain everything about ArrayList โ from basics to internals, common mistakes, confusing behaviors, tricky code examples, and best practices โ in a way that beginners can truly understand.
What is an ArrayList? ๐ง
An ArrayList is a resizable array implementation of the List interface.
In simple terms:
- It behaves like an array
- But its size is not fixed
- It provides many built-in methods for data manipulation
ArrayList is present in the java.util package.
Why Do We Need ArrayList Instead of Arrays? ๐ค
Arrays have several limitations:
- โ Fixed size
- โ No built-in methods for add/remove
- โ Manual resizing required
- โ Less flexible
ArrayList solves these problems:
- โ Dynamic size
- โ Easy insertion and deletion
- โ Rich API methods
- โ Cleaner and safer code
Important Characteristics of ArrayList โญ
- Stores objects only
- Maintains insertion order
- Allows duplicate values
- Allows multiple null values
- Index starts from 0
- Internally uses an array
- Not synchronized (not thread-safe by default)
Internal Working of ArrayList (Very Important) โ๏ธ
Internally, ArrayList uses a normal array.
Key points:
- Default initial capacity is 10
- When the array becomes full:
- A new array is created
- Capacity increases by 50%
- Old elements are copied to the new array
โ Resizing is expensive, so initial capacity matters for performance.
Importing ArrayList ๐ฆ
import java.util.ArrayList;
Without this import, the compiler will throw an error.
Creating an ArrayList ๐๏ธ
ArrayList list = new ArrayList();
โ This creates a raw ArrayList and is not recommended.
Using Generics with ArrayList (Must Know) ๐
ArrayList<Integer> numbers = new ArrayList<>();
Benefits:
- Type safety
- No casting
- Compile-time error checking
Common Mistake: Using Primitive Data Types โ
โ Wrong:
ArrayList<int> list = new ArrayList<>();
โ Correct:
ArrayList<Integer> list = new ArrayList<>();
ArrayList works only with wrapper classes.
Adding Elements to ArrayList โ
ArrayList<String> names = new ArrayList<>();
names.add("Ajay");
names.add("Rahul");
names.add("Neha");
Elements are added at the end by default.
Adding Element at a Specific Index ๐
names.add(1, "Amit");
Elements shift to the right.
โ Invalid index causes IndexOutOfBoundsException.
Accessing Elements from ArrayList ๐
String name = names.get(0);
Index must be within range.
Updating Elements in ArrayList โ๏ธ
names.set(1, "Rohit");
Replaces the existing value at the index.
Removing Elements from ArrayList ๐๏ธ
By index:
names.remove(0);
By value:
names.remove("Neha");
โ Very common confusion:
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.remove(10); // โ tries to remove index 10
list.remove(Integer.valueOf(10)); // โ removes value 10
Size vs Length Confusion ๐ต
โ Correct:
list.size();
โ Wrong:
list.length; // for arrays only
Checking If ArrayList Is Empty ๐ญ
list.isEmpty();
Checking If Element Exists ๐
list.contains(20);
Uses equals() method internally.
Traversing ArrayList Using for Loop ๐
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Traversing Using Enhanced for Loop ๐
for (Integer num : list) {
System.out.println(num);
}
โ Structural modification not allowed.
Traversing Using Iterator ๐งญ
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
โ Safe removal using itr.remove().
Common Mistake: Modifying While Iterating โ
for (Integer num : list) {
list.remove(num); // โ
}
Throws ConcurrentModificationException.
Duplicate and Null Values in ArrayList ๐
list.add(10);
list.add(10);
list.add(null);
list.add(null);
โ Both duplicates and nulls are allowed.
Capacity vs Size (Highly Confusing Topic) ๐งฉ
- Capacity โ internal array size
- Size โ number of elements stored
ArrayList<Integer> list = new ArrayList<>(50);
Capacity = 50
Size = 0
Setting Initial Capacity (Performance Tip) ๐
ArrayList<Integer> list = new ArrayList<>(1000);
Reduces resizing cost.
Converting ArrayList to Array ๐
Integer[] arr = list.toArray(new Integer[0]);
Converting Array to ArrayList ๐
Integer[] arr = {1, 2, 3};
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(arr));
โ Arrays.asList() returns a fixed-size list.
Sorting an ArrayList ๐
Collections.sort(list);
Descending:
Collections.sort(list, Collections.reverseOrder());
ArrayList of Custom Objects ๐จโ๐
class Student {
int id;
String name;
}
ArrayList<Student> students = new ArrayList<>();
Sorting requires Comparable or Comparator.
ArrayList vs Array โ๏ธ
- Array โ Fixed size, faster
- ArrayList โ Dynamic size, flexible
ArrayList vs LinkedList ๐
- ArrayList โ Fast access
- LinkedList โ Fast insertion/deletion
Thread Safety in ArrayList ๐
ArrayList is not thread-safe.
List list = Collections.synchronizedList(new ArrayList<>());
Common Beginner Mistakes Summary โ ๏ธ
- Using
lengthinstead ofsize() - Using primitives instead of wrapper classes
- Confusing
remove(index)andremove(object) - Modifying list during iteration
- Ignoring initial capacity
- Index out of bounds errors
When Should You Use ArrayList? โ
Use ArrayList when:
- Data size is dynamic
- Fast access is required
- Order matters
- Duplicates are allowed
Conclusion ๐ฏ
ArrayList is one of the most important and frequently used classes in Java. It plays a crucial role in real-world applications, interviews, and competitive programming.
Understanding ArrayList deeply โ including its internal working, edge cases, and common mistakes โ builds a strong foundation for mastering Java Collections.
Once you are comfortable with ArrayList, learning other collections like LinkedList, HashSet, and HashMap becomes much easier.
Happy Coding! ๐๐