ArrayList in Java โ€“ Complete Guide for Beginners (With Confusions, Examples & Common Mistakes)

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 length instead of size()
  • Using primitives instead of wrapper classes
  • Confusing remove(index) and remove(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! ๐Ÿš€๐Ÿ˜Š

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *