1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Arraylist
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
01Hrs
21Mins
58Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Arraylist

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
01Hrs
21Mins
58Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

ArrayList

Overview

The ArrayList is the most commonly used data structure in Java, and it solves the primary limitation of standard arrays: fixed size. Once you create an array to hold 5 elements, it can never grow. An ArrayList, on the other hand, is a dynamically resizing ordered collection that automatically grows as you add elements.

Internally, an ArrayList is still backed by a plain int[] array under the hood. When you add elements and the internal array becomes full, it creates a new array roughly 1.5x larger and copies all elements over. This means occasional add operations are O(N), but the amortized cost over many adds is still O(1).

Because ArrayList is part of the Java Collections Framework and works with Generics (using <Type> angle brackets), it is strictly type-safe. You declare ArrayList<String> and the compiler guarantees you can never accidentally add an Integer into it, catching errors at compile time rather than at runtime.

Syntax

Core ArrayList Operations
java
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        
        // 1. Adding Elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add(1, "Mango"); // Insert at index 1
        
        // 2. Accessing Elements
        System.out.println(fruits.get(0)); // "Apple"
        System.out.println("Size: " + fruits.size()); // 4
        
        // 3. Checking and Searching
        System.out.println(fruits.contains("Banana")); // true
        System.out.println(fruits.indexOf("Cherry")); // 2
        
        // 4. Removing Elements
        fruits.remove("Banana");       // Remove by object value
        fruits.remove(0);              // Remove by index
        
        // 5. Iterating
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        
        // 6. Sorting
        Collections.sort(fruits);
        System.out.println(fruits); // Alphabetical order
        
        // 7. Converting to Array
        String[] arr = fruits.toArray(new String[0]);
    }
}

Common Pitfalls

  • Using remove(int index) vs remove(Object o) ambiguity. If you have an ArrayList<Integer> and call list.remove(5), Java resolves it to remove(int index) — removing the element at position 5 — NOT removing the value 5! To remove by value, you must box it: list.remove(Integer.valueOf(5)).
  • Modifying an ArrayList while iterating over it with a for-each loop. This will immediately throw a ConcurrentModificationException. If you need to remove items while iterating, always use an Iterator with iterator.remove(), or use list.removeIf(condition) (Java 8+).
  • Choosing ArrayList when LinkedList would be better. ArrayList is extremely fast for random access (get(i) is O(1)) but slow for insertions/deletions at the middle (O(N) due to element shifting). If your primary operation is inserting/deleting from the middle, LinkedList offers O(1) for those operations.

Interview Questions

What is the time complexity of add(), get(), and remove() in an ArrayList?

add() to the end is amortized O(1), but O(N) when a resize occurs. get(index) is O(1) constant time due to direct array indexing. remove(index) from the middle is O(N) because all elements after it must be shifted one position to the left.

What is the initial default capacity of an ArrayList, and what happens when it's exceeded?

The default initial capacity is 10. When you add an 11th element, Java creates a new internal array with capacity ≈ 15 (1.5× growth), copies all 10 existing elements, then adds the new element. This is why pre-sizing with new ArrayList<>(expectedSize) can significantly improve performance in bulk-loading scenarios.

What is the difference between ArrayList and Vector?

Vector is the legacy (Java 1.0) predecessor to ArrayList. Both are dynamically resizing array-backed lists. The key difference is that all Vector methods are synchronized, making it thread-safe but significantly slower. ArrayList is not synchronized but is far faster in single-threaded contexts. Use Collections.synchronizedList(new ArrayList<>()) for thread-safe ArrayList.

Real-World Example

Almost every backend API returns data as a list. When a product catalog query hits the database, the JDBC result set is iterated and each Product object is added to an ArrayList<Product>. This list is then serialized to JSON and returned in the HTTP response.

example
java
public List<Product> getProductsByCategory(String category) {
    ArrayList<Product> products = new ArrayList<>();
    
    ResultSet rs = db.query("SELECT * FROM products WHERE category=?", category);
    while (rs.next()) {
        products.add(new Product(
            rs.getString("name"),
            rs.getDouble("price")
        ));
    }
    return products; // Serialized to JSON by Spring
}

Check Your Knowledge

Test your understanding of ArrayList with these quick questions.

Question 1

What is the time complexity of `get(index)` on an ArrayList?

Question 2

You have an `ArrayList<Integer>` containing [1, 5, 10]. What does `list.remove(1)` do?

Question 3

What happens if you remove elements from an ArrayList using a for-each loop?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

ArrayList

Overview

The ArrayList is the most commonly used data structure in Java, and it solves the primary limitation of standard arrays: fixed size. Once you create an array to hold 5 elements, it can never grow. An ArrayList, on the other hand, is a dynamically resizing ordered collection that automatically grows as you add elements.

Internally, an ArrayList is still backed by a plain int[] array under the hood. When you add elements and the internal array becomes full, it creates a new array roughly 1.5x larger and copies all elements over. This means occasional add operations are O(N), but the amortized cost over many adds is still O(1).

Because ArrayList is part of the Java Collections Framework and works with Generics (using <Type> angle brackets), it is strictly type-safe. You declare ArrayList<String> and the compiler guarantees you can never accidentally add an Integer into it, catching errors at compile time rather than at runtime.

Syntax

Core ArrayList Operations
java
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        
        // 1. Adding Elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add(1, "Mango"); // Insert at index 1
        
        // 2. Accessing Elements
        System.out.println(fruits.get(0)); // "Apple"
        System.out.println("Size: " + fruits.size()); // 4
        
        // 3. Checking and Searching
        System.out.println(fruits.contains("Banana")); // true
        System.out.println(fruits.indexOf("Cherry")); // 2
        
        // 4. Removing Elements
        fruits.remove("Banana");       // Remove by object value
        fruits.remove(0);              // Remove by index
        
        // 5. Iterating
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        
        // 6. Sorting
        Collections.sort(fruits);
        System.out.println(fruits); // Alphabetical order
        
        // 7. Converting to Array
        String[] arr = fruits.toArray(new String[0]);
    }
}

Common Pitfalls

  • Using remove(int index) vs remove(Object o) ambiguity. If you have an ArrayList<Integer> and call list.remove(5), Java resolves it to remove(int index) — removing the element at position 5 — NOT removing the value 5! To remove by value, you must box it: list.remove(Integer.valueOf(5)).
  • Modifying an ArrayList while iterating over it with a for-each loop. This will immediately throw a ConcurrentModificationException. If you need to remove items while iterating, always use an Iterator with iterator.remove(), or use list.removeIf(condition) (Java 8+).
  • Choosing ArrayList when LinkedList would be better. ArrayList is extremely fast for random access (get(i) is O(1)) but slow for insertions/deletions at the middle (O(N) due to element shifting). If your primary operation is inserting/deleting from the middle, LinkedList offers O(1) for those operations.

Interview Questions

What is the time complexity of add(), get(), and remove() in an ArrayList?

add() to the end is amortized O(1), but O(N) when a resize occurs. get(index) is O(1) constant time due to direct array indexing. remove(index) from the middle is O(N) because all elements after it must be shifted one position to the left.

What is the initial default capacity of an ArrayList, and what happens when it's exceeded?

The default initial capacity is 10. When you add an 11th element, Java creates a new internal array with capacity ≈ 15 (1.5× growth), copies all 10 existing elements, then adds the new element. This is why pre-sizing with new ArrayList<>(expectedSize) can significantly improve performance in bulk-loading scenarios.

What is the difference between ArrayList and Vector?

Vector is the legacy (Java 1.0) predecessor to ArrayList. Both are dynamically resizing array-backed lists. The key difference is that all Vector methods are synchronized, making it thread-safe but significantly slower. ArrayList is not synchronized but is far faster in single-threaded contexts. Use Collections.synchronizedList(new ArrayList<>()) for thread-safe ArrayList.

Real-World Example

Almost every backend API returns data as a list. When a product catalog query hits the database, the JDBC result set is iterated and each Product object is added to an ArrayList<Product>. This list is then serialized to JSON and returned in the HTTP response.

example
java
public List<Product> getProductsByCategory(String category) {
    ArrayList<Product> products = new ArrayList<>();
    
    ResultSet rs = db.query("SELECT * FROM products WHERE category=?", category);
    while (rs.next()) {
        products.add(new Product(
            rs.getString("name"),
            rs.getDouble("price")
        ));
    }
    return products; // Serialized to JSON by Spring
}

Check Your Knowledge

Test your understanding of ArrayList with these quick questions.

Question 1

What is the time complexity of `get(index)` on an ArrayList?

Question 2

You have an `ArrayList<Integer>` containing [1, 5, 10]. What does `list.remove(1)` do?

Question 3

What happens if you remove elements from an ArrayList using a for-each loop?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A